0

I'm having difficulty in understanding the output for the following use of replace in javascript for strings using regex. Please explain the value of 'temp' that will persist.

{
    var temp='xxxx5678';
    var format='x-$2';
    temp= temp.replace(/(x*)([0-9]+)/, format);
    console.log(temp);
}

Here is another sample test case.

{
    var temp='12345678';
    var format='x-$2';
    temp= temp.replace(/(x*)([0-9]+)/, format);
    console.log(temp);
}
1
  • 1
    Use regex101.com for such purposes! I've tested the regex and it works properly. See here Commented Feb 27, 2019 at 19:21

2 Answers 2

2
(x*)([0-9]+)
 |    |
 g1   g2
  • (x*) - Matches x character zero or more time.
  • ([0-9]+) - Matches digits one more time.

So it will replace all any number ( means it can be zero also) of x followed by digits, with format ( x-$2 ) variable.

g1 - will be replaced with x.

g2 - will be replace with whatever [0-9]+ matches

var temp='xxxx5678';
var format='x-$2';
temp= temp.replace(/(x*)([0-9]+)/, format);
console.log(temp);

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

2 Comments

I think you should also mention that $2 in the format gets filled with the second group of the regex match.
@Code Maniac Thnx for the clarification !!
0

I rewrote the code and add notes on Javascript. It would be more clear to learn Javascript replace code and Regex.

var str ='xxxx5678';
result = str.replace(/(x*)([0-9]+)/,'x-$2');
console.log(result);

// str.replace('matech text','replace to')
// (x*)([0-9]+) means two groups $1 and $2. Therefor $2 = ([0-9]+).
// x-$2  replace any string matched (x*)([0-9]+) to "x-" and ([0-9]+).

Comments

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.