2

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?

0

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

Comments

1

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>

1 Comment

It would also fully capture Hello $1 test $2 $3. I guess not what OP wants

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.