最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Regex: How to bold specific words with regex? - Stack Overflow

programmeradmin0浏览0评论

Given a needle and a haystack... I want to put bold tags around the needle. So what regex expression would I use with replace()? I want SPACE to be the delimeter and I want the search to be case insensitive

so say the needle is "cow" and the haystack is

cows at www.cows, milk some COWS

would turn into

<b>cows</b> at www.cows, milk some <b>COWS</b>

also keywords should be able to have spaces in it so if the keyword is "who is mgmt"...

great band. who is mgmt btw? 

would turn into

great band. <b>who is mgmt</b> btw? 

Thanks

Given a needle and a haystack... I want to put bold tags around the needle. So what regex expression would I use with replace()? I want SPACE to be the delimeter and I want the search to be case insensitive

so say the needle is "cow" and the haystack is

cows at www.cows.com, milk some COWS

would turn into

<b>cows</b> at www.cows.com, milk some <b>COWS</b>

also keywords should be able to have spaces in it so if the keyword is "who is mgmt"...

great band. who is mgmt btw? 

would turn into

great band. <b>who is mgmt</b> btw? 

Thanks

Share Improve this question edited Aug 4, 2009 at 23:40 rawrrrrrrrr asked Aug 4, 2009 at 23:34 rawrrrrrrrrrawrrrrrrrr 3,6877 gold badges29 silver badges33 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 16

Here is a regex to do what you're looking for:

(^|\s)(cows)(\s|$)

In JS, replacement is like so:

myString.replace(/(^|\s)(cows)(\s|$)/ig, '$1<b>$2</b>$3');

Wrapped up neatly in a reusable function:

function updateHaystack(input, needle) {
    return input.replace(new RegExp('(^|\\s)(' + needle + ')(\\s|$)','ig'), '$1<b>$2</b>$3');
}

var markup = document.getElementById('somediv').innerHTML;
var output = updateHaystack(markup, 'cows');
document.getElementById('somediv').innerHTML = output;

For those who don't want SPACE as the delimiter, simply don't use \s.

function updateHaystack(input, needle) 
{
 return input.replace(new RegExp('(^|)(' + needle + ')(|$)','ig'), '$1<b>$2</b>$3');
}

Worked for me.

findstring: /(^|\s)(cows)(\s|$)/ig
newstring: '$1<b>$2</b>$3'

The \b markers are for "word boundaries"; the /ig flags are for case-ignoring and global matching, respectively.

The usage of the () captures and then $1/$2/$3 in the new string text is so that the capitalization and spacing of whatever was matched will be preserved.

var needle = 'cows';

var regexp = new RegExp('(^|\s)('+needle+')(\s|$)', 'ig');

var old_string = 'cows at www.cows.com, milk some COWs';

var new_string = old_string.replace(regexp, '<b>$1$2$3</b>');
发布评论

评论列表(0)

  1. 暂无评论