2

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?

3
  • Regular expression.? Commented Feb 10, 2016 at 4:48
  • 1
    Welcome to Stack Overflow! Please see How to Ask and minimal reproducible example. Add your attempts. Commented Feb 10, 2016 at 4:49
  • I was thinking that, but I don't know much about regular expressions. An example would be much appreciated. Commented Feb 10, 2016 at 4:49

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this helped a lot. I ended up using: var slideHeading = $(".slide-heading").text(); $(".slide-heading").html(slideHeading.replace(/\(([^)]+)\)/g, '<strong>$1</strong>')); which did the trick!
0

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 );

2 Comments

split and join will be slower than RegEx.
@Tushar you are correct about performance jsperf.com/split-and-join-vs-regex-1000/2 , but its not too bad actually. In fact regex is slower with bigger strings jsperf.com/split-and-join-vs-regex-1000/3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.