I have a string
test =" abc"
I need to replace the each space between '="' and 'abc' with $ sign. So here it should become
test ="$$$$abc"
I'm trying to do it like this.
str.replace(/(=")(\s+)/g,"$1" + "$2".replace(/\s/g, "$"))
What I intended to do was that with $1 I'm extracting =" part of the string. Then I'm trying to convert the 2nd match of the regular expression($2) to a string. I thought that "$2" will give me the string ' ' after expanding the $2 backreference. Then with that expanded string I'm trying to call replace again in an attempt to convert those spaces to $. After that I'm appending the $1 and the replaced $2 to get ="$$$$. But I realized that $2 does not expand to ' '. Is there some way in which I can manipulate the backreferenced string and use that manipulated version to replace the content of my string.
Thanks for your answer Howard. Anyway I found another way to do it. It seems that you can pass a function as the 2nd argument of the replace function. This function will then be called when a match is found in the string with the parameters matched string, matches in parenthesis if any, offset of the match in the string and the entire string. Then the match will be replaced by the string returned from this function
str. replace(/(=")(\s+)/g, function(match,p1,p2,offset,str){return match.replace(/\s/g,"$")})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With