JavaScript regex to replace words from beginning or whitespace

How can I replace words from beginning of string or from whitespace using JavaScript regex ?
0
give a positive ratinggive a negative rating
12 Dec 2022 at 06:39 PM
Hi,

To replace a words from beginning or whitespace using a Javascript regex pattern, you can use the solution bellow. It is focused on replacement of name, surname or middle name. Becasue it makes some parts bold, it keeps the original values, so it is case insensitive. You can type lowercase letters, uppercase letters or allcaps.

Replace pattern uses \b, which is a word boundry.

The following example may look a bit difficult, but it is quite efficient. It makes one or multiple words in the string bold:

<script>

function replaceWord(content, word) {
var r = new RegExp("(^" + word + "|(?:\\b)" + word + ")", "i");
var p = new RegExp("(\\b)" + word, 'i');
var v = content.replace(r, "<strong>"+ content.substr(content.search(p), word.length) +"</strong>");
return v;
}

var c = replaceWord('Name Middlename Surname', 'middlename');
alert(c);

</script>

0
give a positive ratinggive a negative rating
13 Dec 2022 at 10:26 AM
Tim
Share on FacebookShare on TwitterShare on LinkedInSend email
x
x
2024 AnswerTabsTermsContact us