Max_Salah
Max_Salah

Reputation: 2497

RegExp - replace quote doesn't work

I would like to replace variable str' with <span class="red">str'</span>, but I always get the "'" outeside of the span. I wrote the following javascript:

var f1="XY+X'Y";
var str=X;
var patt=new RegExp(str+'\'',"g");
f1.replace(patt, "<span class=\"red\">"+str+"'"+"</span>")

I get:

<span class="red">X</span>';

I want:

<span class="red">X'</span>;

Upvotes: 1

Views: 199

Answers (2)

Myrddin Emrys
Myrddin Emrys

Reputation: 44005

You are searching for "X'" in your regex, and replacing it with <span ...>X''</span> as far as I can see. There appear to be a few issues with your code, and I'm not sure how you expect to get either result (the one you get, or the one you want) from the given code. May I suggest this alternative?

var f1="XY+X'Y";
var str="X";
var patt=new RegExp(str+"\'?","g");
f1.replace(patt, "<span class=\"red\">$&</span>")

This will find X or X' in the source and surround it with the red class span. If you only want to highlight X', then take out the ? in the patt variable (the ? makes the apostrophe optional).

Edit:

Soluction:

The problem was that I use replace twice on the same string. Something like this

var str =f1.replace(patt, "<span class=\"red\">"+str+"</span>").f1.replace(patt, "<span class=\"red\">"+str+"'"+"</span>")

this works for me:

var str =f1.replace(patt, "<span class=\"red\">"+str+"</span>");
var str2=str.replace(patt, "<span class=\"red\">"+str+"'"+"</span>");

Thanks anyway :)

Upvotes: 0

Chris Carew
Chris Carew

Reputation: 1418

When I evaluate

var f1="XY+X'Y";
var str="X";
var patt=new RegExp(str+'\'',"g");
f1.replace(patt, "<span class=\"red\">"+str+"'"+"</span>")

I get

"XY+<span class="red">X'</span>Y"

Which I think is your intended result? Maybe you just need to double check your quotes/string variables?

Upvotes: 2

Related Questions