ddy250
ddy250

Reputation: 311

Replacing characters at the start and end of a certain string

Suppose this string:

b*any string here*

In case this exists, I want to replace b* at the beginning to <b>, and the * at the end to </b> (Disregard the backslash I need it for escaping on SO site).

Moreover, there might be more then one match:

b*any string here* and after that b*string b*.

These cases should not be handled:

b*foo bar
foo bar*
bb*foo bar* (b is not after a whitespace or beginning of string).

I've gotten this far:

(?<=b\*)(.*?)(?=\*)

This gives me the string in between but Im having difficulties in doing the swap.

Upvotes: 3

Views: 3109

Answers (2)

Jack hardcastle
Jack hardcastle

Reputation: 2875

You could use \b(?:b\*)(.+?)(?:\*), so

const result = yourString.replace(/\b(?:b\*)(.+?)(?:\*)/, "<b>$1</b>");

See the 'Replace' tab https://regexr.com/447cq

Upvotes: 0

ibrahim mahrir
ibrahim mahrir

Reputation: 31682

Use String#replace, you only need to capture the text you want to preserve:

var result = theString.replace(/\bb\*(.*?)\*/g, "<b>$1</b>");

The \b at the begining of the regex means word boundary so that it only matches bs that are not part of a word. $1 means the first captured group (.*?).

Example:

var str1 = "b*any string here* and after that b*string b*.";

var str2 = `b*foo bar
foo bar*
bb*foo bar* (b is not after a whitespace or beginning of string).`;

console.log(str1.replace(/\bb\*(.*?)\*/g, "<b>$1</b>"));

console.log(str2.replace(/\bb\*(.*?)\*/g, "<b>$1</b>"));

Upvotes: 3

Related Questions