I am trying to replace all the occurences of a value in a string and with another value
what I have so far is
var result = "Cooker Works"
var searchterm = "cooker wor";
searchterm.split(" ").forEach(function (item) {
result = result.replace(new RegExp(item, 'g'), "<strong>" + item + "</strong>");
});
console.log(result)
I am trying to replace all the occurences of a value in a string and with another value
what I have so far is
var result = "Cooker Works"
var searchterm = "cooker wor";
searchterm.split(" ").forEach(function (item) {
result = result.replace(new RegExp(item, 'g'), "<strong>" + item + "</strong>");
});
console.log(result)
The result I am after should look like
result = "<strong>Cooker</strong> <strong>Wor</strong>s";
I am having problems handling the case, Is there any way I can ignore this and still get the result I am after
Share Improve this question edited Jul 4, 2017 at 13:55 Ben Thomas 3,2002 gold badges21 silver badges38 bronze badges asked Jul 4, 2017 at 11:46 level_zebralevel_zebra 1,5336 gold badges26 silver badges44 bronze badges4 Answers
Reset to default 7You will get the result you want using capture groups and the i
(ignoreCase) modifier. You can reference the capture group with $1
.
var result = "Cooker Works";
var searchterm = "cooker wor";
searchterm.split(" ").forEach(function(item) {
result = result.replace(new RegExp(`(${item})`, 'ig'), "<strong>$1</strong>");
});
console.log(result)
See MDN for more details: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter
You need to use i
modifier for case-insensitive matching
new RegExp(item, 'ig')
var result = "Cooker Works"
var searchterm = "cooker wor";
searchterm.split(" ").forEach(function(item) {
var matchs = result.match(new RegExp(item, 'ig'));
if (matchs.length)
result = result.replace(new RegExp(item, 'ig'), "<strong>" + matchs[0] + "</strong>");
});
console.log(result)
You need to add case-insensitive modifier. do something like this:
var result = "Cooker Works"
var searchterm = "cooker wor";
searchterm.split(" ").forEach(function (item) {
result = result.replace(new RegExp('(' + item + ')', 'gi'),'<strong>$1</strong>');
});
console.log(result);
This will solve your problem
var result = "Cooker Works"
var searchterm = "cooker wor";
searchterm.split(" ").forEach(function (item) {
result = result.replace(new RegExp(item, 'ig'), "<strong>" + result.match(new RegExp(item, 'ig')) + "</strong>");
});
console.log(result)