简体   繁体   中英

Matching everything after first pipe character in Javascript RegEx

I have this string:

"http://www.yahoo.com/abc/123|X|Y|Z"

I need to get everything after the first pipe with a regex. So I would want to be left with this string:

"X|Y|Z"

How do I do this in JavaScript?

Using a simpler regex

var str = "http://www.yahoo.com/abc/123|X|Y|Z";
var aryMatches = str.match(/\|(.*)/);
// aryMatches[1] will have your results

regex explaination

First group contains the expected characters,

^.*?\|(.*)$

DEMO

You can use this regex:

/^[^|]*\|(.*)/

And use matched group #1 for your match.

Converting my comment to an answer:

Shockingly, regexes are not the answer to everything.

XKCD
> xkcd

Try this:

str.split("|").slice(1).join("|");

This splits your string on pipe characters, slices off the first item, then joins the rest with pipes again.

Forget the splitting and splicing, just use a substring

var str = "http://www.yahoo.com/abc/123|X|Y|Z";
str.substr(str.indexOf("|") + 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM