Force JS replace to work on all occurrences of needle

Please note: This post was written 5 years ago, which is an age in programming terms, so please don't treat this as gospel! I'll be updating all posts soon enough, but if you'd especially like this one to be updated let me know.

I'm more of a cat man myself.

When manipulating strings in JavaScript a useful method to know about is the replace() method. It take 2 parameters - the needle and the haystack. So if you wanted to replace 'cat' with 'dog' it might look something like this:

var myString = "The cat jumped over the fence";
var myNewString = myString.replace("cat","dog");
document.write(myNewString);

Great it worked. You can also use regular expressions for the needle if you're into that kind of thing - say for instance, if you want to generate a valid URL. It when doing just that, that I realised I had a problem on my hands. My code used 2 replace methods - one for removing special characters, the other to remove spaces. The first was a regular expression, while the second was a basic method searching for a space and replacing it with a dash. My problem was that it was only replacing the first space. And so I had to reach for a regular expression to help me out.

Don't worry if you're not too great with RegEx, this one is really basic, and here's what it looks like:

var myString = "The cat jumped over the fence to meet another cat."
var myNewString = myString.replace(/cat+/g,'dog');
document.write(myNewString);

That bit of code tells the rendering engine that we are using a RegEx with our forward slashes, inside we have the word we are looking to replace, then the plus symbol tells it to match the preceding word (in our case 'cat'), 1 or more times. Then the magic happens - we use the 'g' character to tell it to look for all occurrences.

And that is how you ensure all occurrences of a needle are replaced when using the replace() method. Hopefully this article will save you scratching your head over why a seemingly obviously method won't play ball.

***

If you found this particularly useful and want to share the ♥ you can donate here.

***

No Responses



~ Comments are now closed ~

Get in touch here