javascript - How to replace a regular expression match with a $ string with the length of the match - Stack Overflow

I have a string test ="abc"I need to replace the each space between '="' a

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 badges
Add a ment  | 

2 Answers 2

Reset to default 6

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,"$")})

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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信