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);
console.log(result);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Answer from Chandu on Stack OverflowTry 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);
console.log(result);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
String.prototype.replaceAll = function(strReplace, strWith) {
// See http://stackoverflow.com/a/3561711/556609
var esc = strReplace.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var reg = new RegExp(esc, 'ig');
return this.replace(reg, strWith);
};
This implements exactly the example you provided.
'This iS IIS'.replaceAll('is', 'as');
Returns
'Thas as Ias'
String.prototype.replaceAll = function(strReplace, strWith) {
// See http://stackoverflow.com/a/3561711/556609
var esc = strReplace.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var reg = new RegExp(esc, 'ig');
return this.replace(reg, strWith);
};
console.log('This iS IIS'.replaceAll('is', 'as'));
Run code snippetEdit code snippet Hide Results Copy to answer Expand
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>");
}
function highlightWords( line, word )
{
var regex = new RegExp( '(' + word + ')', 'gi' );
return line.replace( regex, "<b>$1</b>" );
}
node.js - How can I perform a case insensitive replace in JavaScript? - Stack Overflow
Javascript | case-insensitive string replace - Stack Overflow
Javascript Replace Making it Case Insensitive - JavaScript - SitePoint Forums | Web Development & Design Community
Case-insensitive string replace-all in JavaScript without a regex - Stack Overflow
- 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>
The approved solution calls toLowerCase inside the loop which is not efficient.
Below is an improved version:
function insensitiveReplaceAll(s, f, r) {
const lcs=s.toLowerCase(), lcf = f.toLowerCase(), flen=f.length;
let res='', pos=0, next=lcs.indexOf(lcf, pos);
if (next===-1) return s;
do {
res+=s.substring(pos, next)+r;
pos=next+flen;
} while ((next=lcs.indexOf(lcf, pos)) !== -1);
return res+s.substring(pos);
}
console.log(insensitiveReplaceAll("Find aBc&deF abcX", "abc", "xy"));
console.log(insensitiveReplaceAll("hello", "abc", "xy"));
Testing with jsPerf - https://jsperf.com/replace-case-insensitive-2/1 - shows it to be 37% faster.
Use String.replace() with a regexp object that has the i (case-insensitive) flag set.
You can safely build a regexp object from an arbitrary string provided that you escape that string first.
$("#tags").val().toLowerCase(); // will convert all uppercase characters to lowercase ones
Then it looks for e.g. ann.c so you'd need to alter the object:
var dictionary = jQuery.parseJSON('[ { "name": "ann.c", "realvalue": "./34534j435345j3b3" }, { "name": "ann.h", "realvalue": "./333dfsdGjh45j3b5" }]');
By the way what about:
var dictionary = [ { "name": "ann.c", "realvalue": "./34534j435345j3b3" },
{ "name": "ann.h", "realvalue": "./333dfsdGjh45j3b5" } ];
http://jsfiddle.net/pimvdb/uDdbq/18/
Simply use a capturing group:
"Javascript vaja".replace(/(ja)/gi, '<b>$1</b>');
See this working demo.
Edit: Read more about capturing groups here.
const input = "Javascript vaja";
const output = input.replace(/ja/gi, '<b>$&</b>');
console.log(output); // <b>Ja</b>vascript va<b>ja</b>