Javascript replaceAll not working
Possible Duplicate:
Replacing all occurrences of a string in javascript?
I need to replace all the string in an variable.
<script>
var a="::::::";
a = a.replace(":","hi");
alert(a);
</script>
Above code replaces only first string ie. hi::::::
I used replaceAll
but its not working.
Please guide me, thanks
There is no replaceAll
in JavaScript: the error console was probably reporting an error .. pay attention!
Instead, use the /g
("match globally") modifier with a regular expression argument to replace
:
var a="::::::";
a = a.replace(/:/g,"hi");
alert(a);
The is covered in MDN: String.replace (and elsewhere).
There is no replaceAll
function in JavaScript.
You can use a regex with a global identifier as shown in pst's answer:
a.replace(/:/g,"hi");
An alternative which some people prefer as it eliminates the need for regular expressions is to use JavaScript's split
and join
functions like so:
a.split(":").join("hi");
It is worth noting the second approach is however slower.
链接地址: http://www.djcxy.com/p/16836.html