Pages

Thursday, 11 February 2016

Replacing all occurrences of a string in JavaScript String replace()



Replacing all occurrences of a string in JavaScript String replace():

<script>
firstString = 'the cat looks like a cat';
replacedString = firstString.replace(/cat/g, 'dog');

document.write(replacedString);
</script>

Result: the dog looks like a dog

explanation: above example all matched words by the name cat were replaced by dog


Now only replace matched first word:

<script>
firstString = 'the cat looks like a cat';
replacedString = firstString.replace('cat', 'dog');

document.write(replacedString);
</script>

Result: the dog looks like a cat

explanation: here first accurate word cat is replaced by dog

No comments:

Post a Comment