admin管理员组文章数量:1332352
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];
本文标签:
版权声明:本文标题:javascript - How to replace a regular expression match with a $ string with the length of the match - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742321293a2452838.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论