JavaScript find and replace all

I was doing some string manipulation the other day using JavaScript. The following code demonstrates the sort of operation I was attempting:

<script type="text/javascript">
    var text = "1234321234321";
    text = text.replace("1", "X");
    alert(text);
</script>

I was expecting the output to be X23432X23432X, but instead got X234321234321. I didn’t realise that the replace method only works on the first instance of the text to be replaced that it finds! I wanted to avoid looping to remove all instances, and instead found this rather nice example on the web that uses regular expressions to replace all instances:

<script type="text/javascript">
    var text = "1234321234321";
    text = text.replace(/1/g, 'X'); 
    alert(text);
</script>

This gives the desired result.

Leave a Reply

Your email address will not be published. Required fields are marked *