I have 开发者_运维百科a string with 3 dollar signs e.g. $$$Test123
. I would like to display this string in a div.
The problem is that when I use replace
I get $$Test123
- 2 dollar signs instead of 3.
example:
var sHtml="<_content_>";
var s="$$$Test";
sHtml= sHtml.replace("<_content_>", s);
Now the result of sHtml
is $$Test
;
Any idea how can it be solved?
javascript does not have a default replace all function. You can write your own like this
function replaceAll(txt, replace, with_this) {
return txt.replace(new RegExp(replace, 'g'),with_this);
}
$
has a special meaning when included in a string for the second argument of a call to replace()
. Normally, you would use it to refer to matched expressions within the original string. For example:
"foo foooo".replace(/fo+/g, "$&bar");
//-> "foobar foooobar"
In the example above, $&
refers back to the entire match, which is foo
in the first word and foooo
in the second.
Your problem stems from the special meaning of $
. In order to use a literal $
in the match, you must chain two together so that the first escapes the second. To have 3 literal $
symbols, you must chain 6 together, like so:
var sHtml="<_content_>";
var s="$$$$$$Test";
sHtml= sHtml.replace("<_content_>", s);
//-> "$$$Test"
Quotes are your friend
var sHtml="<_content_>"
var s="$$$Test";
sHtml= sHtml.replace("<_content_>", s);
Try this replaceAll function:
http://www.dumpsite.com/replaceAll.php
It performs a replace all using the javascript replace function via a regular expression for speed, and at the same time eliminates the side effects that occur when regular expression special characters are inadvertently present in either the search or replace string.
Using this function you do not have to worry about escaping special characters. All special characters are pre escaped before the replaceAll is preformed.
This function will produce the output you are expecting.
Try it out and provide your feeback.
精彩评论