Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 i.e.

"<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"]
like image 423
Varun Muralidharan Avatar asked Jan 17 '13 19:01

Varun Muralidharan


People also ask

Can I use regex in Split in JavaScript?

You do not only have to use literal strings for splitting strings into an array with the split method. You can use regex as breakpoints that match more characters for splitting a string.

How split a string in regex?

split(String regex) method splits this string around matches of the given regular expression. This method works in the same way as invoking the method i.e split(String regex, int limit) with the given expression and a limit argument of zero. Therefore, trailing empty strings are not included in the resulting array.

Is there a split function in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you split a number in JavaScript?

To do this: Convert the number to a string. Call the split() method on the string to convert it into an array of stringified digits. Call the map() method on this array to convert each string to a number.


2 Answers

You may change the greediness with a question mark ?:

"example&ABC56748393&this&is&a&sample&string".split(/&ABC.*?&/);
// ["example", "this&is&a&sample&string"]
like image 149
VisioN Avatar answered Oct 05 '22 10:10

VisioN


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

<string>.split(/<constant_word>.*?&/)
like image 24
ATOzTOA Avatar answered Oct 05 '22 11:10

ATOzTOA