saleh mosleh
saleh mosleh

Reputation: 145

The split string by regex does not work fine in javascript

in javascript i am using split method by regular expression for below string, but it does not work fine in javascript code, also i tested it on some online regex tester website like RegExr and it works fine!

the string: "$1 $2 $3 $5 $7 hello".

the result : ["","$7 ","hello"]

Expected result : ["hello"]

here is my codes: online example!

function myFunction() {
    var str = "$1 $2 $3 $5 $7 hello";
    var res = str.split(/([$][0-9]+[ ]*)+/gu);
    document.getElementById("demo").innerHTML = res;
}
<p>Click the button to display the array value after the split.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

how can i fix it?

Upvotes: 2

Views: 1070

Answers (2)

Khushali jasoliya
Khushali jasoliya

Reputation: 370

function myFunction() {
    var str = "$1 $2 $3 $5 $7 hello $5";
    var subst = ``;
    var res= str.replace(/([$][0-9]?.)/gu, subst);
    document.getElementById("demo").innerHTML = res;
}
<p>Click the button to display the array value after the split.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626920

The capturing group makes the regex engine put back the captured value into the resulting array. Besides, the empty element that results in a match between start of string and the match next to it is added, too.

You can use a non-capturing group and remove empty items afterwards:

var str = "$1 $2 $3 $5 $7 hello";
console.log(str.split(/\s*(?:\$\d+\s*)+/).filter(Boolean));

Pattern details

  • \s* - 0+ whitespaces
  • (?:\$\d+\s*)+ - 1 or more occurrences of
    • \$ - a $ sign
    • \d+ - 1+ digits
    • \s* - 0+ whitespaces.

See the regex demo

Upvotes: 7

Related Questions