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
Is replace case sensitive in JS? In this example, we will see that replace() method is case-sensitive. Output: Learn Node. js on Javatpoint.
The most basic way to do case insensitive string comparison in JavaScript is using either the toLowerCase() or toUpperCase() method to make sure both strings are either all lowercase or all uppercase.
Replace() method allows you to easily replace a substring with another substring, or a character with another character, within the contents of a String object. This method is very handy, but it is always case-sensitive.
Conclusion. To recap, the grep command allows you to search for a pattern inside of files, and is case sensitive by default. To make grep case insensitive, all you have to do is add an -i or —ignore-caseflag.
You 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With