简体   繁体   中英

Split using RegEx in JavaScript

Let's say I have a generalized string

"...&<constant_word>+<random_words_with_random_length>&...&...&..."

I would want to split the string using

"<constant_word>+<random_words_with_random_length>&"

for which I tried RegEx split like

<string>.split(/<constant_word>.*&/)

This RegEx splits till the last '&' unfortunately ie

"<constant_word>+<random_words_with_random_length>&...&...&"

What would be the RegEx code if I wanted it to split when it gets the first '&'?

example for a string split like

"example&ABC56748393&this&is&a&sample&string".split(/ABC.*&/)

gives me

["example&","string"]

while what I want is..

["example&","this&is&a&sample&string"]

You may change the greediness with a question mark ? :

"example&ABC56748393&this&is&a&sample&string".split(/&ABC.*?&/);
// ["example", "this&is&a&sample&string"]

Just use non greedy match, by placing a ? after the * or + :

<string>.split(/<constant_word>.*?&/)

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