I want to replace something (variable -> I call it "x" here) in a text (variable) with 'string'+x+'string'.

My code:

new_content = content.replace(new RegExp(x,"gi"),'string'+x+'string');

So I want to replace upper and lowercase x and the x in 'string'+x+'string'should be lowercase if the search xis lowercase as well. And the same thing for uppercase.

Is there a way like $1 for this situation?

有帮助吗?

解决方案

You can use $& in the replacement string to insert the matched string:

new_content = content.replace(new RegExp(x,"gi"), 'string$&string');
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top