Regular expressions are basically a pattern of characters that can be used to search different occurrences of that pattern in a string. Regular expressions make it possible to search for a particular pattern in a stream of characters and replace it easily. For example, consider the regular expression /ab*c/ which denotes that we are looking for a pattern where we have one ‘a’, followed by 0 or more b characters followed by one ‘c’.
Syntax and Parameters
The syntax of the replace() function is −
Here s is the string in which we want to replace some pattern. Let us look at both the parameters in detail −
pattern − This refers to the sub string of the string s which is to be converted into something else, the sub string that is to be replaced. This parameter can be a string or a regular expression that denotes the pattern to be found and replaced in string s. Only the first occurrence of the pattern in s will be replaced, but if a regular expression is provided with the global modifier ‘g’ in this parameter, all matches of that regular expression in the string s will be replaced. Naturally, this is a required parameter.
replacement − This denotes the string which will take the place of the pattern in the string s. This is what every occurrence of the pattern will be replaced with. Note that this parameter can also be a function that returns the string which will be used as a replacement for each occurrence of pattern in s.
This function gives another string with the required replacements as output. For example,
The resulting string will change from "abcdea" to "bbcdea" after this operation. Note that the last a was not replaced as the regular expression provided as a pattern does not contain the global modifier ‘g’.
Let us take a look at how we can achieve this through the code for both with and without the global modifier ‘g’.
Example 1: Without the global modifier ‘g’.
In the below example, we replace a string using the string replace() method without global modifier 'g'.
<!DOCTYPE html> <html> <body> <script> var st = "She sells sea shells on the seashore"; document.write("Original string : " + st); var regExp = /Sea/i; var modifiedSt = st.replace(regExp, "river"); document.write("<br>Modified string : " + modifiedSt); </script> </body> </html>
Example 2: With the globab modifier ‘g’.
In the below example, we replace a string using the string replace() method with global modifier 'g'.
<!DOCTYPE html> <html> <body> <script> var st = "She sells sea shells on the seashore"; document.write("Original string : " + st); var regExp = /Sea/ig; var modifiedSt = st.replace(regExp, "river"); document.write("<br>Modified string : " + modifiedSt); </script> </body> </html>
- Related Articles
- How to replace Digits into String using Java?
- Replace a string using StringBuilder
- How i can replace number with string using Python?