JavaScript Page 5 - Understanding the JavaScript RegExp Object |
The previous set of examples highlighted the search capabilities of the String object. But that's not all! You can also perform a search-and-replace operation with the replace() method, which accepts both a regular expression and the value to replace it with. Here's how:
If you load this example in a browser, you will see that the string "Anderson" has been replaced with the string "Smith". The following output illustrates: Welcome to the Matrix, Mr. Smith Remember how I used the "g" modifier to search for multiple instances of a pattern within a string? Take it one step further - you can even use it to replace multiple instances of a pattern within the string:
Here, the \s metacharacter matches the space after "yo" and "ho" and replaces with "oo". You can also use case-insensitive pattern matching - simply add the "i" modifier (for "insensitive") at the end of the pattern. The next example shows you how:
blog comments powered by Disqus |