I have a string
test =" abc"
I need to replace the each space between '="' and 'abc' with $ sign. So here it should bee
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.
I have a string
test =" abc"
I need to replace the each space between '="' and 'abc' with $ sign. So here it should bee
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.
Share Improve this question asked Jul 13, 2011 at 17:50 Jophin JosephJophin Joseph 2,9534 gold badges30 silver badges41 bronze badges2 Answers
Reset to default 6Thanks 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,"$")})
You can use the function match
and join the result afterwards.
m = str.match(/(.*)(=")(\s+)(.*)/);
str = m[1]+m[2]+m[3].replace(/\s/g, "$")+m[4];
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742321293a4421862.html
评论列表(0条)