Luke Thornton
Luke Thornton

Reputation: 23

Replacing a specific character with a html tag in jQuery

I'm trying to style a specific word in a string by wrapping it in a <strong></strong> tag. The problem is that This word will change all the time, so I was thinking of getting them to wrap the particular word in brackets (in an input text field), and then replace the opening and closing brackets with the opening and closing strong tags.

Eg:

"Who said (romance) was dead?"

would become

"Who said <strong>romance</strong> was dead?"

What would be the best way to go about this?

Upvotes: 2

Views: 365

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115282

You can use replace() with capturing group regex

console.log(
  "Who said (romance) was dead?".replace(/\(([^)]+)\)/g, '<strong>$1</strong>')
);

/\(([^)]+)\)/g

Above regex will match all the string in between ( and ) and repcace the captured group data surround with <strong> tag.

Regex explanation here

Regular expression visualization

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68443

if an answer without regex is acceptable to you then try :)

var str = "Who said (romance) was dead?";

var wordToBeStronged = "romance";

str = str.split( "(" + wordToBeStronged + ")" ).join( "<strong>" + wordToBeStronged + "</strong>" );

console.log( str );

Upvotes: 0

Related Questions