Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a regular expression match with a $ string with the length of the match

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.

like image 579
Jophin Joseph Avatar asked Jul 13 '11 17:07

Jophin Joseph


1 Answers

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,"$")})
like image 74
Jophin Joseph Avatar answered Nov 04 '22 11:11

Jophin Joseph