'a cat is not a cool-cat'.replace(/\bcat\b/gi,'dog');//wrong//"a dog is not a cool-dog" -- nips'a cat is not a cool-cat'.replace(/(?:\b([^-]))cat(?:\b([^-]))/gi,'$1dog$2');//"a dog is not a cool-cat"
var oops = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/cat/g,'dog');//returns "the dog looks like a dog, not a dogerpillar or cooldog" ??
var caterpillar = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");//return "the dog looks like a dog, not a caterpillar or coolcat"
function replaceMulti(haystack, needle, replacement){return haystack.split(needle).join(replacement);}
someString = 'the cat looks like a cat';console.log(replaceMulti(someString, 'cat', 'dog'));
/*** Replace all the occerencess of $find by $replace in $originalString* @param {originalString} input - Raw string.* @param {find} input - Target key word or regex that need to be replaced.* @param {replace} input - Replacement key word* @return {String} Output string*/function replaceAll(originalString, find, replace) {return originalString.replace(new RegExp(find, 'g'), replace);};
// Consider the below exampleoriginalString.replace(/stringToBeReplaced/gi, '');
// The output will be all the occurrences removed irrespective of casing.
function replaceAll(s, find, repl, caseOff, byChar) {if (arguments.length<2)return false;var destDel = ! repl; // If destDel delete all keys from targetvar isString = !! byChar; // If byChar, replace set of charactersif (typeof find !== typeof repl && ! destDel)return false;if (isString && (typeof find !== "string"))return false;
if (! isString && (typeof find === "string")) {return s.split(find).join(destDel ? "" : repl);}
if ((! isString) && (! Array.isArray(find) ||(! Array.isArray(repl) && ! destDel)))return false;
// If destOne replace all strings/characters by just one elementvar destOne = destDel ? false : (repl.length === 1);
// Generally source and destination should have the same sizeif (! destOne && ! destDel && find.length !== repl.length)return false
var prox, sUp, findUp, i, done;if (caseOff) { // Case insensitive
// Working with uppercase keys and targetsUp = s.toUpperCase();if (isString)findUp = find.toUpperCase()elsefindUp = find.map(function(el) {return el.toUpperCase();});}else { // Case sensitivesUp = s;findUp = find.slice(); // Clone array/string}
done = new Array(find.length); // Size: number of keysdone.fill(null);
var pos = 0; // Initial position in target svar r = ""; // Initial resultvar aux, winner;while (pos < s.length) { // Scanning the targetprox = Number.MAX_SAFE_INTEGER;winner = -1; // No winner at the startfor (i=0; i<findUp.length; i++) // Find next occurence for each stringif (done[i]!==-1) { // Key still alive
// Never search for the word/char or is over?if (done[i] === null || done[i] < pos) {aux = sUp.indexOf(findUp[i], pos);done[i] = aux; // Save the next occurrence}elseaux = done[i] // Restore the position of last search
if (aux < prox && aux !== -1) { // If next occurrence is minimumwinner = i; // Save itprox = aux;}} // Not done
if (winner === -1) { // No matches forwardr += s.slice(pos);break;} // No winner
// Found the character or string key in the target
i = winner; // Restore the winnerr += s.slice(pos, prox); // Update piece before the match
// Append the replacement in targetif (! destDel)r += repl[destOne ? 0 : i];pos = prox + (isString ? 1 : findUp[i].length); // Go after match} // Loop
return r; // Return the resulting string}
留档如下:
replaceAll
Syntax======
replaceAll(s, find, [repl, caseOff, byChar)
Parameters==========
"s" is a string target of replacement."find" can be a string or array of strings."repl" should be the same type than "find" or empty
If "find" is a string, it is a simple replacement forall "find" occurrences in "s" by string "repl"
If "find" is an array, it will replaced each string in "find"that occurs in "s" for corresponding string in "repl" array.The replace specs are independent: A replacement part cannotbe replaced again.
If "repl" is empty all "find" occurrences in "s" will be deleted.If "repl" has only one character or element,all occurrences in "s" will be replaced for that one.
"caseOff" is true if replacement is case insensitive(default is FALSE)
"byChar" is true when replacement is based on set of characters.Default is false
If "byChar", it will be replaced in "s" all characters in "find"set of characters for corresponding character in "repl"set of characters
Return======
The function returns the new string after the replacement.
function l() {return console.log.apply(null, arguments);}
var k = 0;l(++k, replaceAll("banana is a ripe fruit harvested near the river",["ri", "nea"], ["do", "fa"])); // 1l(++k, replaceAll("banana is a ripe fruit harvested near the river",["ri", "nea"], ["do"])); // 2l(++k, replaceAll("banana is a ripe fruit harvested near the river",["ri", "nea"])); // 3l(++k, replaceAll("banana is a ripe fruit harvested near the river","aeiou", "", "", true)); // 4l(++k, replaceAll("banana is a ripe fruit harvested near the river","aeiou", "a", "", true)); // 5l(++k, replaceAll("banana is a ripe fruit harvested near the river","aeiou", "uoiea", "", true)); // 6l(++k, replaceAll("banana is a ripe fruit harvested near the river","aeiou", "uoi", "", true)); // 7l(++k, replaceAll("banana is a ripe fruit harvested near the river",["ri", "nea"], ["do", "fa", "leg"])); // 8l(++k, replaceAll("BANANA IS A RIPE FRUIT HARVESTED NEAR THE RIVER",["ri", "nea"], ["do", "fa"])); // 9l(++k, replaceAll("BANANA IS A RIPE FRUIT HARVESTED NEAR THE RIVER",["ri", "nea"], ["do", "fa"], true)); // 10return;
以及结果:
1'香蕉是远在多佛收获的毒品水果' 2'香蕉是多佛收获的一种毒品水果' 3'香蕉是收获的一种水果' 4'bnn s rp frt hrvstd nr th rvr' 5'banana as a rapa fraat哈佛' 6'bununu is u ripo frait hurvostod nour tho rivor' 7 false 8 false 9“香蕉是河边采摘的熟果” 10'香蕉是多佛收获的多普水果'
var str = '[{"id":1,"name":"karthikeyan.a","type":"developer"}]'var i = str.replace('"[','[').replace(']"',']');console.log(i,'//first element search and replace')
在字符串中全局搜索和替换
var str = '[{"id":1,"name":"karthikeyan.a","type":"developer"}]'var j = str.replace(/\"\[/g,'[').replace(/\]\"/g,']');console.log(j,'//global search and replace')
var str = "Test abc test test abc test test test abc test test abc";
var result = str.split(' ').reduce((a, b) => {return b == 'abc' ? a : a + ' ' + b; })
console.warn(result)
let str = "Test abc test test abc test test test abc test test abc";
str = str.split(" ");str = str.filter((ele, key)=> ele!=="abc")str = str.join(" ")
或者干脆-
str = str.split(" ").filter((ele, key) => ele != "abc").join(" ")
const str = "Test abc test test abc test test test abc test test abc";
const compare = "abc";arrayStr = str.split(" ");arrayStr.forEach((element, index) => {if (element == compare) {arrayStr.splice(index, 1);}});const newString = arrayStr.join(" ");console.log(newString);
function replaceAll(searchString, replaceString, str) {return str.split(searchString).join(replaceString);}
replaceAll('abc', '',"Test abc test test abc test test test abc test test abc" ); // "Test test test test test test test test "
<!DOCTYPE html><html><body><p>Click the button to do a global search and replace for "is" in a string.</p><button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() {var str = 'Is this "3" dris "3"?';var allvar= '"3"';var patt1 = new RegExp( allvar, 'g' );document.getElementById("demo").innerHTML = str.replace(patt1,'"5"');}</script></body></html>
var annoyingString = "Test abc test test abc test test test abc test test abc";
while (annoyingString.includes("abc")) {annoyingString = annoyingString.replace("abc", "")}
String.prototype.replaceAll = function(search, replace){return this.replace(new RegExp(search, 'g'), replace)}
var str = "Test abc test test abc test test test abc test test abc";str = str.replaceAll('abc', '');
console.log(str) // -> Test test test test test test test test
if (!Object.prototype.hasOwnProperty.call(RegExp, 'escape')) {RegExp.escape = function(string) {// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping// https://github.com/benjamingr/RegExp.escape/issues/37return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string};}
if (!Object.prototype.hasOwnProperty.call(String, 'replaceAll')) {String.prototype.replaceAll = function(find, replace) {// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll// If you pass a RegExp to 'find', you _MUST_ include 'g' as a flag.// TypeError: "replaceAll must be called with a global RegExp" not included, will silently cause significant errors. _MUST_ include 'g' as a flag for RegExp.// String parameters to 'find' do not require special handling.// Does not conform to "special replacement patterns" when "Specifying a string as a parameter" for replace// Does not conform to "Specifying a function as a parameter" for replacereturn this.replace(Object.prototype.toString.call(find) == '[object RegExp]' ?find :new RegExp(RegExp.escape(find), 'g'),replace);}}
if (!Object.prototype.hasOwnProperty.call(String, 'replaceAll')) {String.prototype.replaceAll = function(find, replace) {// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll// If you pass a RegExp to 'find', you _MUST_ include 'g' as a flag.// TypeError: "replaceAll must be called with a global RegExp" not included, will silently cause significant errors. _MUST_ include 'g' as a flag for RegExp.// String parameters to 'find' do not require special handling.// Does not conform to "special replacement patterns" when "Specifying a string as a parameter" for replace// Does not conform to "Specifying a function as a parameter" for replacereturn this.replace(Object.prototype.toString.call(find) == '[object RegExp]' ?find :new RegExp(find.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'), 'g'),replace);}}
/* Iterate over table data cells to insert a highlight tag */function highlightSearchResults(textFilter) {textFilter = textFilter.toLowerCase().replace('<', '<').replace('>', '>');let tds;tb = document.getElementById('sometable'); //root element where to searchif (tb) {tds = tb.getElementsByTagName("td"); //sub-elements where to make replacements}if (textFilter && tds) {for (td of tds) {//specify your span class or whatever you need before and aftertd.innerHTML = insertCaseInsensitive(td.innerHTML, textFilter, '<span class="highlight">', '</span>');}}}
/* Insert a highlight tag */function insertCaseInsensitive(srcStr, lowerCaseFilter, before, after) {let lowStr = srcStr.toLowerCase();let flen = lowerCaseFilter.length;let i = -1;while ((i = lowStr.indexOf(lowerCaseFilter, i + 1)) != -1) {if (insideTag(i, srcStr)) continue;srcStr = srcStr.slice(0, i) + before + srcStr.slice(i, i+flen) + after + srcStr.slice(i+flen);lowStr = srcStr.toLowerCase();i += before.length + after.length;}return srcStr;}
/* Check if an ocurrence is inside any tag by index */function insideTag(si, s) {let ahead = false;let back = false;for (let i = si; i < s.length; i++) {if (s[i] == "<") {break;}if (s[i] == ">") {ahead = true;break;}}for (let i = si; i >= 0; i--) {if (s[i] == ">") {break;}if (s[i] == "<") {back = true;break;}}return (ahead && back);}
if (!String.prototype.replaceAll) { // Check if the native function not existObject.defineProperty(String.prototype, 'replaceAll', { // Define replaceAll as a prototype for (Mother/Any) Stringconfigurable: true, writable: true, enumerable: false, // Editable & non-enumerable property (As it should be)value: function(search, replace) { // Set the function by closest input names (For good info in consoles)return this.replace( // Using native String.prototype.replace()Object.prototype.toString.call(search) === '[object RegExp]' // IsRegExp?? search.global // Is the RegEx global?? search // So pass it: function(){throw new TypeError('replaceAll called with a non-global RegExp argument')}() // If not throw an error: RegExp(String(search).replace(/[.^$*+?()[{|\\]/g, "\\$&"), "g"), // Replace all reserved characters with '\' then make a global 'g' RegExpreplace); // passing second argument}});}
if (!String.prototype.replaceAll) { // Check if the native function not existObject.defineProperty(String.prototype, 'replaceAll', { // Define replaceAll as a prototype for (Mother/Any) Stringconfigurable: true, writable: true, enumerable: false, // Editable & non-enumerable property (As it should be)value: function(search, replace) { // Set the function by closest input names (For good info in consoles)return this.replace( // Using native String.prototype.replace()Object.prototype.toString.call(search) === '[object RegExp]' // IsRegExp?? search.global // Is the RegEx global?? search // So pass it: RegExp(search.source, /\/([a-z]*)$/.exec(search.toString())[1] + 'g') // If not, make a global clone from the RegEx: RegExp(String(search).replace(/[.^$*+?()[{|\\]/g, "\\$&"), "g"), // Replace all reserved characters with '\' then make a global 'g' RegExpreplace); // passing second argument}});}
if(!String.prototype.replaceAll){Object.defineProperty(String.prototype,'replaceAll',{configurable:!0,writable:!0,enumerable:!1,value:function(search,replace){return this.replace(Object.prototype.toString.call(search)==='[object RegExp]'?search.global?search:RegExp(search.source,/\/([a-z]*)$/.exec(search.toString())[1]+'g'):RegExp(String(search).replace(/[.^$*+?()[{|\\]/g,"\\$&"),"g"),replace)}})}
console.log('Change this and this for me'.replaceAll('this','that')); // Change that and that for me
console.log('aaaaaa'.replaceAll('aa','a')); // aaa
console.log('{} (*) (*) (RegEx) (*) (\*) (\\*) [reserved characters]'.replaceAll('(*)','X')); // {} X X (RegEx) X X (\*) [reserved characters]
console.log('How (replace) (XX) with $1?'.replaceAll(/(xx)/gi,'$$1')); // How (replace) ($1) with $1?
console.log('Here is some numbers 1234567890 1000000 123123.'.replaceAll(/\d+/g,'***')); // Here is some numbers *** *** *** and need to be replaced.
console.log('Remove numbers under 233: 236 229 711 200 5'.replaceAll(/\d+/g, function(m) {return parseFloat(m) < 233 ? '' : m})); // Remove numbers under 233: 236 711
console.log('null'.replaceAll(null,'x')); // x
// The difference between My first preference and the original:// Now in 2022 with browsers > 2020 it should throw an error (But possible it be changed in future)
// console.log(// 'xyz ABC abc ABC abc xyz'.replaceAll(/abc/i,'')// );
// Browsers < 2020:// xyz xyz// Browsers > 2020// TypeError: String.prototype.replaceAll called with a non-global RegExp