JavaScript will replace all ignoring case sensitivity

I am trying to replace all occurrences of a value in a string with another value

what i still

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)
Run codeHide result

As a result, I should look like

result = "<strong>Cooker</strong> <strong>Wor</strong>s";

I'm having trouble processing the case. Is there a way to ignore this and still get the result after

+4
source share
4 answers

You will get the result you want to use capture groups, and the modifier i(ignoreCase). You can reference a 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)
Run codeHide 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

+3

i

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)
Hide result
+6

You need to add a 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);
Run codeHide result
+2
source

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)
Run codeHide result
+1
source

Source: https://habr.com/ru/post/1680715/


All Articles