Reputation: 23
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
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.
Upvotes: 1
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