Reputation: 1293
Consider I have a string like this, and I want to append html tags before and after a specific keyword in the string.
let name = "George William";
let keyword = "geo";
After appending the html tags, i want to get result like this,
<strong>Geo</strong>rge William
I tried something like this,
name.replace(new RegExp(keyword, 'gi'), "<strong>"+keyword+"</strong>");
But it results like this,
<strong>geo</strong>rge William
How can i get the result with exact "case" in the original name?
Upvotes: 1
Views: 623
Reputation: 947
You can refer to the matched substring in your result using $&
let name = 'George William';
let keyword = 'geo';
console.log(name.replace(new RegExp(keyword, 'gi'), '<strong>$&</strong>'));
Upvotes: 1
Reputation: 3747
This isn't the prettiest code I have ever written, but it doesn't use Regular Expressions and it does work for ignoring the case, while making this a re-usable function that doesn't have to be tied to the <strong>
tag specifically.
let name = "George William";
let keyword = "geo";
const newHtml = (str, key, tagName) => {
return str.toLowerCase()
.split(key.toLowerCase())
.map((val) => {
if (val !== '') {
return val;
}
else {
let idx = str.toLowerCase().indexOf(key.toLowerCase());
return `<${tagName}>${str.split('').slice(idx, key.length).join('')}</${tagName}>`;
}
})
.join('');
};
console.log(newHtml(name, keyword, 'strong'));
Upvotes: 2