Generally, "replace" method in java script replaces only the first occurrence in the given string. We can change this behaviour by using regular expression.
 
<html>
<script type='text/javascript'>
var str='webtestdevelopmenttestscripts.com';
var rpl=str.replace(/test/g,' ');
alert('Result:'+rpl);
document.write(rpl);
</script>
</html>

Above example matches "test" and replaces with a space in the javascript variable "str". "g" in the regex pattern refers global match, so it matches all the occurences of the given string and replaces. To make this replace method case insensitive, add "i" to the regex pattern like this:
var rpl=str.replace(/test/gi,' ');

 


Comments (0)
Leave a Comment

loader Posting your comment...