Reputation: 7340
I'm new to regular expressions...
I've a search string, and result from querying the database.
in Javascript how can search the string and emphasize or bold it.
let's say
q="dolor";
result = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, Lorem ipsum dolor sit amet, consectetur adipiscing elit, Lorem ipsum dolor sit amet, consectetur adipiscing elit";
the end string should have
Lorem ipsum <em>dolor</em> sit amet, consectetur adipiscing elit, Lorem ipsum <em>dolor</em> sit amet, consectetur adipiscing elit, Lorem ipsum <em>dolor</em> sit amet, consectetur adipiscing elit
Upvotes: 0
Views: 177
Reputation: 99081
Try this:
var sentence = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, Lorem ipsum dolor sit amet, consectetur adipiscing elit, Lorem ipsum dolor sit amet, consectetur adipiscing elit";
var match = "dolor";
var replace = "<em>"+match+"</em>";
var regexp = new RegExp(match, "gi");
var output = sentence.replace(regexp, replace);
alert(output);
Upvotes: 1
Reputation: 70750
I would use a word boundary \b
around your pattern and then do the replacement.
var re = new RegExp("\\b" + q + "\\b", "gi");
result = result.replace(re, "<em>" + q + "</em>");
Upvotes: 1
Reputation: 225281
If your search string isn’t a regular expression, you can use split
and avoid escaping issues:
result.split(q).join('<em>' + q + '</em>')
<mark>
, by the way, might be more appropriate.
Case-insensitive is not so simple, but I still wouldn’t use a regular expression:
function highlight(text, find) {
var lowercaseText = text.toLowerCase();
var lowercaseFind = find.toLowerCase();
var result = '';
var lastIndex = 0;
var i;
while ((i = lowercaseText.indexOf(lowercaseFind, lastIndex)) !== -1) {
result +=
text.substring(lastIndex, i) +
'<em>' + text.substring(i, i + find.length) + '</em>';
lastIndex = i + find.length;
}
return result + text.substring(lastIndex);
}
It lends itself well to working with the DOM, too.
Upvotes: 0
Reputation: 4295
Here's a nice simple function that should do the trick, just pass the database string and the substring to this function and it will return a new string with all instances of the substring wrapped in <em>
tags
function emphasize(str, sub) {
return str.replace(new RegExp(sub, 'g'), '<em>' + sub + '</em>');
}
var str = "Teenage mutant JavaScript ninja. Loves JavaScript",
sub = "JavaScript";
emphasize(str, sub);
=> 'Teenage mutant <em>JavaScript</em> ninja. Loves <em>JavaScript</em>'
Upvotes: 0
Reputation: 71
Refer to the string replace command as described in: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
result = result.replace(/(dolor)/g, '<em>$1</em>');
Upvotes: 0