How can I find a specific word in a string then replace it using javascript?
For example
JavaScript
x
2
1
This is a very long sentence
2
I would like to find the word “sentence” and replace it by “phrase”, so the output would be
JavaScript
1
2
1
This is a very long phrase
2
Advertisement
Answer
Yes, just use replace
:
JavaScript
1
5
1
var input = prompt("Enter a sentence");
2
3
var boldTest = "sentence";
4
5
document.write(input.replace(boldTest, `<strong>${boldTest}</strong>`));
In the above example, boldTest
is whatever word you want to replace.