Reputation: 3657
var keyword = 'test';
var replaced = $(".test-section").html().replace(new RegExp(keyword, "igm"),'<span class="greenbackground">'+keyword+'</span>');
$(".test-section").html(replaced);
I want to highlight a keyword of my paragraph. The above code is working well except, if i have 'testing'
in my div
content, even that is getting the class. how can i make my code test only for specific string. please find the same issue on fiddle
Upvotes: 0
Views: 58
Reputation: 1074258
If you're happy with JavaScript's definition of a word boundary, you can use \b
:
var keyword = 'test';
var replaced = $(".test-section").html().replace(new RegExp("\\b" + keyword + "\\b", "igm"),'<span class="greenbackground">'+keyword+'</span>');
$(".test-section").html(replaced);
But check JavaScript's definition of a word character, it may surprise you, it's very English-centric. Specifically, it's the 26 English letters A-Z (upper or lower case), the digits 0-9, or an underscore. Anything else (é
, for instance), is not a "word" character according to JavaScript.
any alphanumeric character including the underscore. Equivalent to [A-Za-z0-9_].
If you want to apply your own definition, you can use an alternations within capture groups to test for "beginning of line or non-word character" and "end of line or non-word character", and include the captured text (if any) in the replacement.
var keyword = 'test';
var replaced = $(".test-section").html().replace(new RegExp("(^|\\W)" + keyword + "($|[^\\w])", "igm"),'$1<span class="greenbackground">'+keyword+'</span>$2');
$(".test-section").html(replaced);
In that example, for "your definition of a non-word character" I've used \W
, which is JavaScript's "not a word character," but of course you'd want to adjust that (otherwise, you'd just use the \b
solution shown earlier). Note the $1
at the beginning of the replacement, and the $2
at the end — those are where we put the characters we matched before and after the word (if any) back.
If you need to do a test that you can't express in a regular expression, you can use the function callback on replace
:
var keyword = 'test';
var replaced = $(".test-section").html().replace(new RegExp("(^|.)" + keyword + "($|[^.])", "igm"), function(m, c1, c2) {
// Here, c1 will be the character before your keyword, or "" at beginning of line;
// c2 will be the character after your keyword, or "" at end of line.
// Return the new string to replace the match with.
// So for instance:
if (/*...your definition says c1 and c2 are not word characters...*/) {
// Update this occurrence:
return c1 + '<span class="greenbackground">'+keyword+'</span>' + c2;
} else {
// Leave it unchanged (in effect)
return m;
}
});
$(".test-section").html(replaced);
Beware "keywords" with characters in them that are special for regular expressions. Since you're using new RegExp
, if your keyword were (say) $span
, that would look like the end-of-line marker $
followed by span
.
Upvotes: 2