Skip to content
Advertisement

How to find and replace a string in Javascript? [closed]

How can I find a specific word in a string then replace it using javascript?

For example

This is a very long sentence

I would like to find the word “sentence” and replace it by “phrase”, so the output would be

This is a very long phrase

Advertisement

Answer

Yes, just use replace:

var input = prompt("Enter a sentence");

var boldTest = "sentence";

document.write(input.replace(boldTest, `<strong>${boldTest}</strong>`));

In the above example, boldTest is whatever word you want to replace.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement