The simple way is to use regular expression with string
replace() method to replace all instances of a string in a given text. This method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.
If you specify a value (instead of a regular expression), only the first occurrence of the value will be replaced. To replace all occurrences (case-sensitive) of a specified value, we can use a regular expression with global modifier (
To perform a global case-insensitive replacement, we have to pass
i flag in addition to
Split and Join
split() method converts the string into an array of substrings based on a specified value (case-sensitive), and returns the array. If an empty string is used an the separator, the string is split between each character. This method does not alter the original string.
If you want to perform a global case-insensitive split, you can use regular expression:
join() method does the opposite of the
split() method. It joins the elements of an array into a string, and returns the string. We can specify a join separator. The default separator is comma.
token.join('Java'); //"Java is Java!"
Both split and join operations can be combined like the following:
In this tutorial, we have discussed two different approaches to replace all occurrences of a string in a text. You can either use regular expression or
replace() method is simple and faster.
If you have any question or feedback, please feel free to send me a tweet anytime.
Happy Coding 😍
Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: firstname.lastname@example.org.