Case insensitive replace all
Try regex:
'This iS IIS'.replace(/is/ig, 'as');
Working Example: http://jsfiddle.net/9xAse/
e.g:
Using RegExp object:
var searchMask = "is";
var regEx = new RegExp(searchMask, "ig");
var replaceMask = "as";
var result = 'This iS IIS'.replace(regEx, replaceMask);
Javascript | case-insensitive string replace
With a case-insensitive regular expression:
function boldString(str, find) { var reg = new RegExp('('+find+')', 'gi'); return str.replace(reg, '<b>$1</b>');}console.log(boldString('Apple', 'ap'))
How can I perform a case insensitive replace in JavaScript?
You need to pass <b>$&</b>
as the second parameter to .replace
to insert the matched substring:
const string = "The quick brown fox jumped over the lazy QUICK dog";console.log( string.replace(/quick/gi, '<b>$&</b>'));
Case insensitive string replacement in JavaScript?
You can use regular expressions if you prepare the search string. In PHP e.g. there is a function preg_quote, which replaces all regex-chars in a string with their escaped versions.
Here is such a function for javascript (source):
function preg_quote (str, delimiter) {
// discuss at: https://locutus.io/php/preg_quote/
// original by: booeyOH
// improved by: Ates Goral (https://magnetiq.com)
// improved by: Kevin van Zonneveld (https://kvz.io)
// improved by: Brett Zamir (https://brett-zamir.me)
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// example 1: preg_quote("$40")
// returns 1: '\\$40'
// example 2: preg_quote("*RRRING* Hello?")
// returns 2: '\\*RRRING\\* Hello\\?'
// example 3: preg_quote("\\.+*?[^]$(){}=!<>|:")
// returns 3: '\\\\\\.\\+\\*\\?\\[\\^\\]\\$\\(\\)\\{\\}\\=\\!\\<\\>\\|\\:'
return (str + '')
.replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&')
}
So you could do the following:
function highlight(str, search) {
return str.replace(new RegExp("(" + preg_quote(search) + ")", 'gi'), "<b>$1</b>");
}
Case-insensitive string replace-all in JavaScript without a regex
- Start with an empty string and copy the original string.
- Find the index of the string to replace in the copy (setting them both to lowercase makes the search case-insensitive).
- If it's not in the copy, skip to step 7.
- Add everything from the copy up to the index, plus the replacement.
- Trim the copy to everything after the part you're replacing.
- Go back to step 2.
- Add what's left of the copy.
Just for fun I've created an interactive version where you can see the results of both a regex and indexOf, to see if escaping a regex breaks anything. The method used to escape the regex I took from jQuery UI. If you have it included on the page it can be found with $.ui.autocomplete.escapeRegex
. Otherwise, it's a pretty small function.
Here's the non-regex function, but since the interactive section adds a lot more code I have the full code snippet hidden by default.
function insensitiveReplaceAll(original, find, replace) {
var str = "",
remainder = original,
lowFind = find.toLowerCase(),
idx;
while ((idx = remainder.toLowerCase().indexOf(lowFind)) !== -1) {
str += remainder.substr(0, idx) + replace;
remainder = remainder.substr(idx + find.length);
}
return str + remainder;
}
// example call:
insensitiveReplaceAll("Find aBcc&def stuff ABCabc", "abc", "ab");
function insensitiveReplaceAll(original, find, replace) { var str = "", remainder = original, lowFind = find.toLowerCase(), idx;
while ((idx = remainder.toLowerCase().indexOf(lowFind)) !== -1) { str += remainder.substr(0, idx) + replace;
remainder = remainder.substr(idx + find.length); }
return str + remainder;}
function escapeRegex(value) { return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");}
function updateResult() { var original = document.getElementById("original").value || "", find = document.getElementById("find").value || "", replace = document.getElementById("replace").value || "", resultEl = document.getElementById("result"), regexEl = document.getElementById("regex");
if (original && find && replace) { regexEl.value = original.replace(new RegExp(escapeRegex(find), "gi"), replace); resultEl.value = insensitiveReplaceAll(original, find, replace); } else { regexEl.value = ""; resultEl.value = ""; }
}
document.addEventListener("input", updateResult);window.addEventListener("load", updateResult);
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<div class="input-group input-group-sm"> <span class="input-group-addon">Original</span> <input class="form-control" id="original" value="Find aBcc&def stuff ABCabc" /></div>
<div class="input-group input-group-sm"> <span class="input-group-addon">Find</span> <input class="form-control" id="find" value="abc" /></div>
<div class="input-group input-group-sm"> <span class="input-group-addon">Replace</span> <input class="form-control" id="replace" value="ab" /></div>
<div class="input-group input-group-sm"> <span class="input-group-addon">Result w/o regex</span> <input disabled class="form-control" id="result" /></div>
<div class="input-group input-group-sm"> <span class="input-group-addon">Result w/ regex</span> <input disabled class="form-control" id="regex" /></div>
javascript replace all with case insensitive and keeping correct case in original string
Simply use a capturing group:
"Javascript vaja".replace(/(ja)/gi, '<b>$1</b>');
See this working demo.
Edit: Read more about capturing groups here.
JavaScript replaceAll case-insensitive search using variable rather than a string
Basically, what you want is to create a dynamic regular expression, instead of hardcoding it. This is done with the help of. RegExp constructor, which takes the string representation of a regexp and flags (I messed the string capitalization to demo the preservation of case):
string1 = 'DnA deoxyribonucleic acid'
string2 = 'DNA deoxyribonucleic aCId'
const replacer = (str, replace) => {
const re = new RegExp(`(${replace})`, 'gi')
return str.replaceAll(re, '***$1***')
}
console.log(replacer(string1, 'dna'))
console.log(replacer(string2, 'acid'))
JavaScript replace all ignoring case sensitivity
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)
Replace values from an array in string non case sensitive in javascript
maybe you can use regex
let array = ['mate']
let string = 'Hello Mate, how are you mate?'
let re = new RegExp(array.join("|"),"gi");
let str = string.replace(re, 'censored');
output:
"Hello censored, how are you censored?"
change part of the string with case sensitive
var querystr = 'first';
var output = "FiRst Last";
var reg = new RegExp(querystr, 'gi');
var final_str = output.replace(reg, function(str) {return str.bold().fontcolor("Blue")});
See this following link...
Javascript: highlight substring keeping original case but searching in case insensitive mode
Solution give by user113716 may helpful...
Related Topics
Wrapping Lines/Polygons Across the Antimeridian in Leaflet.Js
Filtering an Array with a Function That Returns a Promise
Date Parsing in JavaScript Is Different Between Safari and Chrome
Create a File Using JavaScript in Chrome on Client Side
Selecting Multiple Classes with Jquery
Fetching All (Javascript) Global Variables in a Page
Code with Classlist Does Not Work in Ie
How to Convert CSV to JSON in Node.Js
Js Strings "+" VS Concat Method
Get Query String Parameters Url Values with Jquery/JavaScript (Querystring)
React - Getting a Component from a Dom Element for Debugging
How to Make 'Setinterval' Behave More in Sync, or How to Use 'Settimeout' Instead
How to Debug JavaScript with Ie 8
Angular2 Component's "This" Is Undefined When Executing Callback Function
React Input Defaultvalue Doesn't Update with State