The string is a simple text or characters which can include the alphabets, numbers, or symbols.
Syntax for the replace() method is
substring can be any value from the string to which we want to replace
newstring is the value that replaces the substring(first parameter).
Now, if we take a look at some examples. We suppose a string “Linuxhint is great and linuxhint is working great.”. In this string, I have repeated the same word “great” and “linuxhint” intentionally. The purpose of this will be right in front of you in a moment. Now, let’s try to replace the word “great” with let’s say “awesome” using the replace() method.
Here you can see the problem that the first occurrence of “great” gets replaced. But, the second one doesn’t. So, here comes the concept of the regular expression. We can also give the regular expression instead of the substring to the replace() method.
So let’s modify the syntax a little bit that we can give regular expression as well.
regex is a regular expression object. The matches will be replaced by the newstring.
If we want to replace every single occurrence of the word “great” then we shall pass the regular expression with a ‘g’ flag, which is a short form for global. Take a look below to get an idea about what exactly I mean.
Perfect, all the occurrences of “great” are changed. But, now we may face a problem if we try to change all the occurrences of “linuxhint” to let’s say “our website” using the same technique. Let’s try to do that first, then we will see how can we resolve that.
As you can see that. Although we have provided the global flag with the regular expression. But, the first occurrence doesn’t get changed. This is because of case-sensitivity. So, we need to provide a case-insensitivity flag ‘i’. We can do that by simply adding the ‘i’ flag along with the ‘g’ flag. Like,
Great. As you can see that all the occurrences of “linuxhint” are changed regardless of the case-sensitivity.
We have two protips for you. One is that we can give multiple substrings in a regular expression as well using the OR “|” operator. The second one is that we can also provide a function instead of the newstring. So, the final syntax that you should take with you is
Let’s have a look at an example. To understand how it works.
In this example, we will change/replace both “great” & “linuxhint” using a single replace method and later we will provide some tasks to do in a function, in which we will change the matches to the uppercase.
Alright! As you can see that both of the words “great” & “linuxhint” are converted into the uppercase letters, successfully.