0

On my website I have multiple occurrences of a string with always the same substring (let's say "boo-foo", "loo-foo" and "great-foo").

I want to replace all of those with firstpart-foo. So the first part of all those should be bold.

Can anyone provide a regex for that in jQuery?

I believe it should look something like this, but with regex:

$(this).html($(this).html.replace("boo-foo","<strong>boo-</strong>foo"));

3 Answers 3

2

Please check this script,

var htmlText = $('body').html();
var replaced = htmlText.replace(/([\w\d]+)\-foo/ig, "<strong>$1</strong>-foo");
$('body').html(replaced);

Fiddle: https://jsfiddle.net/o6doa4o6/

Updated Fiddle to make "-" bold as well.

https://jsfiddle.net/o6doa4o6/1/

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

Comments

0
$(this).html($(this).html().replace(/^(.*)\-foo$/ig,'<strong>$1</strong>-foo');

Comments

0

You can use the back Reference to look for the captured group and then use the string.replace method to replace the string using a Regex. Backreferences allows to reference the text which was previously matched by a capturing group. In javascript you can make use of $1 to reference the first captured group. Similarly $2, $3.. for each captured group.

Following implementation shows this behavior, excluding the Jquery part.

var stringValue = `boo-foo
loo-foo
great-foo`;

var regexToSearch = /([a-zA-Z]*)-foo/g;

var result = stringValue.replace(regexToSearch, '<strong>$1</strong>-foo');
console.log(result);

Comments

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.