0

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
Aymane Hrouch
  • 103
  • 1
  • 11
  • 4
    Possible duplicate of [Simple javascript find and replace](https://stackoverflow.com/questions/5983681/simple-javascript-find-and-replace) – MTCoster Feb 10 '19 at 22:06

2 Answers2

1

replace()

The following demo
⬥ Uses the Regex method replace(),
⬥ Uses a RegExp Object for dynamic variable search key,
⬥ Has thorough input escaping,
⬥ Is able to find all matches of a given search key,
⬥ and it wraps matched text with the <mark> element (it can be easily changed to <strong>).

findText(selector, key);

First parameter is a selector string of the element with the text to be searched. Syntax is exactly like CSS/jQuery selectors:

"#id", ".class", "tagName", "[name=name]"

The second parameter is the search keyword in the form of a string.


Demo

function findText(selector, key) {
  var node = document.querySelector(selector);
  var str = node.textContent;
  var esc = `(?!(?:[^<]+>|[^>]+<\\/a>))\\b(${key})\\b`;
  var rgx = new RegExp(esc, "g");
  var txt = str.replace(rgx, `<mark>$1</mark>`);
  return node.innerHTML = txt;
}

findText('p', 'Duis');
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
Community
  • 1
  • 1
zer00ne
  • 41,936
  • 6
  • 41
  • 68
0

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.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79