In meinen Anwendungen verwende ich eine benutzerdefinierte Funktion, die für diesen Zweck am leistungsfähigsten ist, und sogar das Wrapping der split/join
Lösung im einfacheren Fall, sie ist ein wenig schneller in Chrome 60
et Firefox 54
( JSBEN.CH
) als andere Lösungen. Mein Computer läuft Windows 7 64 bits
.
Der Vorteil ist, dass diese benutzerdefinierte Funktion viele Ersetzungen gleichzeitig verarbeiten kann, indem sie Zeichenketten oder Zeichen verwendet, was für einige Anwendungen eine Abkürzung sein kann.
Wie ein split/join
Im Gegensatz zur obigen Lösung hat die folgende Lösung kein Problem mit Escape-Zeichen, anders als der Ansatz des regulären Ausdrucks.
function replaceAll(s,find,repl,caseOff,byChar){
if (arguments.length<2) return false;
var destDel = ! repl; // if destDel delete all keys from target
var isString = !! byChar; // if byChar, replace set of characters
if (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 element
var destOne = destDel ? false : (repl.length===1);
// Generally source and destination should have the same size
if (! destOne && ! destDel && find.length!==repl.length) return false
var prox,sUp,findUp,i,done;
if (caseOff) { // case insensitive
// Working with uppercase keys and target
sUp = s.toUpperCase();
if (isString)
findUp = find.toUpperCase()
else
findUp = find.map(function(el){ return el.toUpperCase();});
} else { // case sensitive
sUp = s;
findUp =find.slice(); // clone array/string
}
done = new Array(find.length); // size: number of keys
done.fill(null);
var pos = 0; // initial position in target s
var r = ""; // initial result
var aux, winner;
while (pos < s.length) { // Scanning the target
prox = Number.MAX_SAFE_INTEGER;
winner = -1; // no winner at start
for (i=0;i<findUp.length;i++) // find next occurence for each string
if (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
} else
aux = done[i] // restore the position of last search
if (aux<prox && aux!==-1) { // if next occurrence is minimum
winner = i; // save it
prox = aux;
}
} // not done
if (winner===-1) { // No matches forward
r += s.slice(pos);
break;
} // no winner
// found the character or string key in the target
i = winner; // restore the winner
r += s.slice(pos,prox); // update piece before the match
// Append the replacement in target
if (! destDel) r += repl[ destOne?0:i ];
pos = prox + ( isString?1:findUp[i].length ); // go after match
} // loop
return r; // return the resulting string
}
Die Dokumentation finden Sie unten
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 for
all "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 cannot
be 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.
Um fair zu sein, habe ich die Benchmark ohne Parameterprüfung.
Hier ist mein Testsatz, mit Node.js
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"])); //1
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
["ri","nea"],["do"])); //2
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
["ri","nea"])); //3
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
"aeiou","","",true)); //4
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
"aeiou","a","",true)); //5
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
"aeiou","uoiea","",true)); //6
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
"aeiou","uoi","",true)); //7
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
["ri","nea"],["do","fa","leg"])); //8
l(++k,replaceAll("BANANA IS A RIPE FRUIT HARVESTED NEAR THE RIVER",
["ri","nea"],["do","fa"])); //9
l(++k,replaceAll("BANANA IS A RIPE FRUIT HARVESTED NEAR THE RIVER",
["ri","nea"],["do","fa"],true)); //10
return;
Und die Ergebnisse:
1 "Die Banane ist eine Dopingfrucht, die weit entfernt vom Meer geerntet wird.
2 "Die Banane ist eine dope Frucht, die für den Dover geerntet wird".
3 "Die Banane ist eine Pe-Frucht, die auf dem Land geerntet wird.
4 'bnn s rp frt hrvstd nr th rvr'
5 "Banane als rapa fraat harvastad naar tha ravar".
6 'bununu is u ripo frait hurvostod nour tho rivor'
7 falsch
8 falsch
9 "DIE BANANE IST EINE REIFE FRUCHT, DIE IN DER NÄHE DES FLUSSES GEERNTET WIRD".
10 "BANANE IST EINE DOPPELFrucht, die vom DONNER geerntet wird".