简体   繁体   中英

Javascript replace() removing one of the two special characters

Replacing {t} in the variable var2, removes a '$' symbol from var1 and renders it as abc$abc instead of abc$$abc in the final result.

var var1 = 'abc$$abc';
var var2 = 'You are comparing {t} entity';
$('#div1').append('<div id="div2">' + var2.replace('{t}','<a href="' + var1 + '" target="_self">' + '</a>') + '</div>');

The closest questions I could find was Javascript append element with special characters , but even that couldn't address the problem.

Undoubtedly, I can check if the resultant string contains just one $ of two $s but i want to know if there is anything wrong with append above, as well as, if there is any generic way to achieve the result with the resultant string being restored with two $ signs.

$$ is a replacement pattern in String.replace() which is always replaced by a single $ . You need to double all dollar signs:

var var1 = 'abc$$abc'.replace( /\$/g, '$$$$' );

(Four dollar signs because again they act as replacement patterns.)

$ has special meaning in javascript string replace. When you use $$ you are basically escaping one of them. If you'd like two you can use four $$$$

To make your code work specifically, I think this would be about the most simple thing:

var var1 = 'abc$$abc'.split("$").join("$$");

JSFiddle

See here for details on $ in replace() : Mozilla docs


Figured I'd insert my comments here as well:

If you need to make sure this is done during the {t} replace (if the string may change after initialization) you can just throw it in like this:

$('#div1').append('<div id="div2">' + 
    var2.replace('{t}','<a href="' + 
        var1.split("$").join("$$") + 
        '" target="_self">' + '</a>')
+ '</div>');

or if this is something that needs to be done often in various places... you could create your own function for it... like:

function replaceEscapingDollars(str, find, replacement) { 
    return str.replace(find, replacement.split("$").join("$$"));
}

then your code would look like:

$('#div1').append('<div id="div2">' + 
    replaceEscapingDollars(var2, '{t}', '<a href="' + var1 + '" target="_self">' + '</a>') +
'</div>');

JSFiddle


But the simplest thing of all might be just to not use replace at all...

var2.split('{t}').join(var1)

JSFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM