To search and replace a text in JavaScript, we can use the replace()
function. The replace()
function can use regular expressions to find patterns in a string.
Here is an example of how to use replace()
function to replace a word "World" in a string "Hello World" with "JavaScript":
index.tsx133 chars4 lines
In the above code, we first declare a string myString
with the value "Hello World". Then we use the replace()
function to replace the word "World" with "JavaScript". The replace()
function returns a new string with the replaced value, which we assign back to the myString
variable. Finally, we log the output to the console.
Here is another example using regular expressions to find and replace all occurrences of "World" in a string:
index.tsx196 chars4 lines
In the above code, we declare a string myString
with the value "Hello World, Hello World, Hello World". Then we use the replace()
function with a regular expression /World/g
to find all occurrences of "World" in the string and replace them with "JavaScript". The /g
flag in the regular expression stands for "global", which means it will replace all occurrences of the pattern in the string. Finally, we log the output to the console.
gistlibby LogSnag