The in-built function in JavaScript is the ".replace()" function.
The syntax of the .replace() function is as follows:
" <string_name>.replace('text to edit', 'text to replace it with' ); "
Hence, in a string, the whole or part of the string can be replaced with some other value using this in-built function.
For example, let the string s be: "I practice development with the help of the Coding Ninjas website." And the code is as follows:
let news=s.replace("website", "Website");
Then, if we print the string news, it will be as follows:
"I practice development with the help of the Coding Ninjas Website."
Also, you can use it multiple times to replace various texts of the string located in different positions.
Like,
let news=s
.replace("development", "Development")
.replace("with", "With");
console.log(news);
These statements will result in the following output:
"I practice Development With the help of the Coding Ninjas website."
Also, if there is more than one instance of the text you have written that you want to replace with some other text, only the first instance of the text will be replaced.
For example,
let news = s.replace("the", "The");
console.log(news);
It will only replace the first 'the', resulting as follows:
"I practice development with The help of the Coding Ninjas website."
Hence, if you want to replace all the instances of a substring of the string, you would have to use the ".replaceAll()" method.
Now, if you want to replace multiple substrings with one text, you can use the following syntax of the commands:
let news = s.replace(/practice|development/g, "study");
console.log(news);
The output will be:
"I study study with the help of the Coding Ninjas website."
Also, you can try the following syntax of the command to use the ".replace()" function with regular expressions.
let news=s.replace(/the/g, "The");
console.log(news);
The output of these commands will be as the following:
"I practice development with The help of The Coding Ninjas website."
Here, the "/g" specifies that all the occurrences of the substring "the" should be replaced with "The" substring.