JavaScripts replace() Function Only Replacing First Occurrence
The replace() function in JavaScript is useful for finding a substring within a string and replacing it with a new substring. What the official JavaScript documentation doesn’t state very clearly however is that the function will only replace the first occurrence. But what if we need to perform a global find and replace and swap out all occurrences?
The Solution
To swap out all cases of a substring we need to use a regular expression and add the identifier ‘g’ to end of the substring that we are looking for. For example:
var str = "This is sample text for a sample replace"; str = str.replace(/sample/g, "lovely"); alert(str);
You should be returned with ‘This is lovely text for a lovely replace’. Note how there are no quotes used around the substring parameter. Instead the substring is contained with forward slashes and the ‘g’ regular expression indentifier prepended to the end.
Related Posts
- Perform a Mass MySQL Find and Replace in a Single Query- Swap and Re-Order Divs Smoothly Using jQuery – Swapsies Plugin
- Foreign Characters in Javascript Alert Showing Question Mark In Diamond
- Grab a Client’s Attention: A Cool Little Javascript Number Input Box
- Detect Leaving Visitors with jQuery
Hi, I'm Steve Marks, the voice (or at least the typist) behind this blog. I'm 24 and currently live in the UK.
Thanks man, it worked perfectly!