userden
userden

Reputation: 1683

How to make many words bold in a sentence with regex?

I'm using regex to replace double underscores around a word into a bold tag. But if I have more then one word bolded in a sentence, then it doesn't work. For example:

 "this should be __bold__ and __this__ also".replace(/\__([^*]+)\__/g,"<b>$1</b>");

I get this:

 "this should be <span>bold__ and __this</span> also"

But I would like to get this:

 "this should be <span>bold</span> and <span>this</span> also"

There is something wrong with my regex. At the moment it only works, if there is a single bold word in a sentence.

Upvotes: 0

Views: 192

Answers (3)

Khauri
Khauri

Reputation: 3863

As a slightly different solution, try this regex:

/__(.*?)__/g

See the explanation here: https://regex101.com/r/7CVJyd/1

let str = "this should be __bold__ and __this__ also";
str = str.replace(/__(.*?)__/g,"<b>$1</b>");

console.log(str);

Upvotes: 0

Nicholas
Nicholas

Reputation: 156

Do you replace double underscores to bold tags like __this__ becomes <b>this</b>? You can do this,

"this should be __bold__ and __this__ also".replace(/__([^ ]+)__/g,"<b>$1</b>");

Instead of [^*], you do [^ ] to exclude all whitespaces.

Upvotes: 0

Wazner
Wazner

Reputation: 3102

In Regex the quantifiers + and * are "greedy", this means they will consume as many characters as possible that match the expression being quantified. You can append the question mark operator ? to turn a "greedy" operation into a lazy operation.

This would make your expression as follows:

/\__([^*]+?)\__/g

For more information check out http://www.regular-expressions.info/repeat.html#lazy

Upvotes: 2

Related Questions