سؤال

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