Ho questa stringa:
"Test abc test test abc test test test abc test test abc"
Fare
str = str.replace('abc', '');
sembra rimuovere solo la prima occorrenza di abc
nella stringa sopra. Come posso sostituire tutti occorrenze di esso?
Per completezza, ho avuto modo di pensare a quale metodo dovrei usare per farlo. Ci sono fondamentalmente due modi per farlo come suggerito dalle altre risposte in questa pagina.
Nota: In generale, l'estensione dei prototipi incorporati in JavaScript non è generalmente raccomandata. Fornisco come estensioni del prototipo String semplicemente a scopo illustrativo, mostrando diverse implementazioni di un ipotetico metodo standard sul prototipo String
integrato.
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.split(search).join(replacement);
};
Non sapendo troppo su come le espressioni regolari funzionino dietro le quinte in termini di efficienza, tendevo a propendere per la divisione e unire l'implementazione in passato senza pensare alle prestazioni. Quando mi sono chiesto quale fosse più efficiente e con quale margine, l'ho usato come scusa per scoprirlo.
Sul mio computer Windows 8 di Chrome, l'implementazione basata su espressioni regolari è la più veloce, con l'implementazione split e join che è del 53% più lenta. Significa che le espressioni regolari sono due volte più veloci per l'ingresso di lorem ipsum che ho usato.
Controlla questo benchmark eseguendo queste due implementazioni l'una contro l'altra.
Come notato nel commento seguente di @ThomasLeduc e altri, potrebbe esserci un problema con l'implementazione basata su espressioni regolari se search
contiene determinati caratteri che sono riservati come caratteri speciali nelle espressioni regolari . L'implementazione presuppone che il chiamante sfugga alla stringa in anticipo o passerà solo le stringhe senza i caratteri nella tabella in Regular Expressions (MDN).
MDN fornisce anche un'implementazione per sfuggire alle nostre stringhe. Sarebbe bello se questo fosse anche standardizzato come RegExp.escape(str)
, ma ahimè, non esiste:
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
Potremmo chiamare escapeRegExp
all'interno della nostra implementazione String.prototype.replaceAll
, tuttavia, non sono sicuro di quanto questo influenzi le prestazioni (potenzialmente anche per le stringhe per cui l'escape non è necessario, come tutte le stringhe alfanumeriche).
str = str.replace(/abc/g, '');
In risposta al commento:
var find = 'abc';
var re = new RegExp(find, 'g');
str = str.replace(re, '');
In risposta a Fai clic sul commento di Upvote , puoi semplificarlo ancora di più:
function replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}
Nota: Le espressioni regolari contengono caratteri speciali (meta), e come tale è pericoloso passare ciecamente un argomento nella funzione find
in alto senza pre-elaborarlo per evitare quei caratteri. Questo è trattato in Mozilla Developer Network 's JavaScript Guide on Regular Expressions , dove presentano la seguente funzione di utilità:
function escapeRegExp(str) {
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
Quindi, al fine di rendere la funzione replaceAll()
sopra più sicura, potrebbe essere modificata a quanto segue se includi anche escapeRegExp
:
function replaceAll(str, find, replace) {
return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
Nota: non usare questo nel codice reale.
In alternativa alle espressioni regolari per una semplice stringa letterale, puoi usare
str = "Test abc test test abc test...".split("abc").join("");
Lo schema generale è
str.split(search).join(replacement)
In alcuni casi questo metodo era più veloce rispetto all'utilizzo di replaceAll
e un'espressione regolare, ma ciò non sembra più il caso nei browser moderni. Quindi, questo dovrebbe essere usato solo come un trucco rapido per evitare di dover sfuggire all'espressione regolare, non nel codice reale.
L'uso di un'espressione regolare con il flag g
sostituirà tutto:
someString = 'the cat looks like a cat';
anotherString = someString.replace(/cat/g, 'dog');
// anotherString now contains "the dog looks like a dog"
Ecco una funzione di prototipo di stringa basata sulla risposta accettata:
String.prototype.replaceAll = function (find, replace) {
var str = this;
return str.replace(new RegExp(find, 'g'), replace);
};
MODIFICARE
Se il tuo find
conterrà caratteri speciali, dovrai sfuggire a loro:
String.prototype.replaceAll = function (find, replace) {
var str = this;
return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};
Fiddle: http://jsfiddle.net/cdbzL/
Aggiornare:
È un po 'tardi per un aggiornamento, ma da quando mi sono imbattuto in questa domanda e ho notato che la mia risposta precedente non è una di cui sono felice. Poiché la domanda riguardava la sostituzione di una singola parola, è incredibile che nessuno abbia pensato di utilizzare i limiti di Word (\b
)
'a cat is not a caterpillar'.replace(/\bcat\b/gi,'dog');
//"a dog is not a caterpillar"
Questa è una semplice regex che evita di sostituire parti di parole nella maggior parte dei casi. Tuttavia, un trattino -
è ancora considerato un confine di Word. Quindi in questo caso è possibile utilizzare condizionali per evitare di sostituire stringhe come cool-cat
:
'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"
fondamentalmente, questa domanda è la stessa della domanda qui: Javascript sostituisce "'" con "' '"
@ Mike, controlla la risposta che ho dato lì ... regexp non è l'unico modo per sostituire più occorrenze di un subsrting, lontano da esso. Pensa flessibile, pensa dividi!
var newText = "the cat looks like a cat".split('cat').join('dog');
In alternativa, per evitare la sostituzione di parti di Word, anche la risposta approvata lo farà! Puoi aggirare questo problema usando espressioni regolari che, lo ammetto, sono un po 'più complesse e, come risultato, anche un po' più lento:
var regText = "the cat looks like a cat".replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");
L'output è uguale alla risposta accettata, tuttavia, usando l'espressione/cat/g su questa stringa:
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" ??
Oso davvero, questo probabilmente non è quello che vuoi. Cos'è, allora? IMHO, una regex che sostituisce solo "gatto" in modo condizionale. (cioè non parte di una parola), in questo modo:
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"
La mia ipotesi è che questo soddisfi le tue esigenze. Naturalmente non è completamente protetto, ma dovrebbe essere sufficiente per iniziare. Consiglierei di leggerne un po 'di più su queste pagine. Ciò si rivelerà utile per perfezionare questa espressione per soddisfare le tue esigenze specifiche.
http://www.javascriptkit.com/jsref/regexp.shtml
http://www.regular-expressions.info
Aggiunta finale:
Dato che questa domanda ottiene ancora molte visualizzazioni, ho pensato di aggiungere un esempio di .replace
utilizzato con una funzione di callback. In questo caso, semplifica drasticamente l'espressione e fornisce ancora più flessibilità, come la sostituzione con la corretta maiuscola o la sostituzione di cat
e cats
in una volta sola:
'Two cats are not 1 Cat! They\'re just cool-cats, you caterpillar'
.replace(/(^|.\b)(cat)(s?\b.|$)/gi,function(all,char1,cat,char2)
{
//check 1st, capitalize if required
var replacement = (cat.charAt(0) === 'C' ? 'D' : 'd') + 'og';
if (char1 === ' ' && char2 === 's')
{//replace plurals, too
cat = replacement + 's';
}
else
{//do not replace if dashes are matched
cat = char1 === '-' || char2 === '-' ? cat : replacement;
}
return char1 + cat + char2;//return replacement string
});
//returns:
//Two dogs are not 1 Dog! They're just cool-cats, you caterpillar
Corrisponde a un'espressione regolare globale:
anotherString = someString.replace(/cat/g, 'dog');
str = str.replace(/abc/g, '');
Oppure prova la funzione replaceAll da qui:
Quali sono i metodi JavaScript utili che estendono gli oggetti incorporati?
str = str.replaceAll('abc', ''); OR
var search = 'abc';
str = str.replaceAll(search, '');
EDIT: Chiarimento su replaceAll availability
Il metodo 'replaceAll' viene aggiunto al prototipo di String. Ciò significa che sarà disponibile per tutti gli oggetti stringa/letterali.
Per esempio.
var output = "test this".replaceAll('this', 'that'); //output is 'test that'.
output = output.replaceAll('that', 'this'); //output is 'test this'
Supponi di voler sostituire tutti 'abc' con 'x':
let some_str = 'abc def def lom abc abc def'.split('abc').join('x')
console.log(some_str) //x def def lom x x def
Stavo cercando di pensare a qualcosa di più semplice della modifica del prototipo di stringa.
Usa un'espressione regolare:
str.replace(/abc/g, '');
Sostituire le virgolette singole:
function JavaScriptEncode(text){
text = text.replace(/'/g,''')
// More encode here if required
return text;
}
Questi sono i metodi più comuni e leggibili.
var str = "Test abc test test abc test test test abc test test abc"
Metodo 01:
str = str.replace(/abc/g, "replaced text");
Metodo 02:
str = str.split("abc").join("replaced text");
Metodo 03:
str = str.replace(new RegExp("abc", "g"), "replaced text");
Metodo 04:
while(str.includes("abc")){
str = str.replace("abc", "replaced text");
}
Produzione:
console.log(str);
// Test replaced text test test replaced text test test test replaced text test test replaced text
// loop fino a quando le occorrenze del numero arrivano a 0. OR semplicemente copia/incolla
function replaceAll(find, replace, str)
{
while( str.indexOf(find) > -1)
{
str = str.replace(find, replace);
}
return str;
}
Questa è la versione più veloce che non usa espressioni regolari.
replaceAll = function(string, omit, place, prevstring) {
if (prevstring && string === prevstring)
return string;
prevstring = string.replace(omit, place);
return replaceAll(prevstring, omit, place, string)
}
È quasi due volte veloce come il metodo split e join.
Come indicato in un commento qui, questo non funzionerà se la variabile omit
contiene place
, come in: replaceAll("string", "s", "ss")
, perché sarà sempre in grado di sostituire un'altra occorrenza della Parola.
C'è un altro jsperf con varianti sul mio sostituto ricorsivo che vanno ancora più veloce ( http://jsperf.com/replace-all-vs-split-join/12 )!
str = str.replace(new RegExp("abc", 'g'), "");
ha funzionato meglio per me rispetto alle risposte di cui sopra. così new RegExp("abc", 'g')
crea un RegExp che corrisponde a tutte le occorrenze ('g'
flag) del testo ("abc"
). La seconda parte è ciò che viene rimpiazzato, nel tuo caso stringa vuota (""
) .str
è la stringa, e dobbiamo sovrascriverla, poiché replace(...)
restituisce solo i risultati, ma non le sostituzioni. In alcuni casi potresti volerlo usare.
Usando RegExp
in JavaScript potrebbe fare il lavoro per te, semplicemente fai qualcosa come di seguito, non dimenticare /g
dopo il quale standout per global :
var str ="Test abc test test abc test test test abc test test abc";
str = str.replace(/abc/g, '');
Se pensi di riutilizzare, crea una funzione per farlo per te, ma non è raccomandato in quanto è solo una funzione di linea, ma ancora una volta se usi pesantemente questo, puoi scrivere qualcosa come questo:
String.prototype.replaceAll = String.prototype.replaceAll || function(string, replaced) {
return this.replace(new RegExp(string, 'g'), replaced);
};
e semplicemente usarlo nel tuo codice più e più volte come di seguito:
var str ="Test abc test test abc test test test abc test test abc";
str = str.replaceAll('abc', '');
Ma come detto in precedenza, non farà un'enorme differenza in termini di righe da scrivere o prestazioni, solo il caching della funzione potrebbe avere delle prestazioni più veloci su stringhe lunghe e anche una buona pratica del codice DRY se voglio riutilizzare.
Se ciò che vuoi trovare è già in una stringa, e non hai un'erogazione delle espressioni regolari a portata di mano, puoi usare join/split:
function replaceMulti(haystack, needle, replacement)
{
return haystack.split(needle).join(replacement);
}
someString = 'the cat looks like a cat';
console.log(replaceMulti(someString, 'cat', 'dog'));
function replaceAll(str, find, replace) {
var i = str.indexOf(find);
if (i > -1){
str = str.replace(find, replace);
i = i + replace.length;
var st2 = str.substring(i);
if(st2.indexOf(find) > -1){
str = str.substring(0,i) + replaceAll(st2, find, replace);
}
}
return str;
}
Mi piace questo metodo (sembra un po 'più pulito):
text = text.replace(new RegExp("cat","g"), "dog");
var str = "ff ff f f a de def";
str = str.replace(/f/g,'');
alert(str);
while (str.indexOf('abc') !== -1)
{
str = str.replace('abc', '');
}
Se la stringa contiene pattern simili come abccc
, puoi usare questo:
str.replace(/abc(\s|$)/g, "")
Le risposte precedenti sono troppo complicate. Basta usare la funzione di sostituzione in questo modo:
str.replace(/your_regex_pattern/g, replacement_string);
Esempio:
var str = "Test abc test test abc test test test abc test test abc";
var res = str.replace(/[abc]+/g, "");
console.log(res);
Se stai cercando di assicurarti che la stringa che stai cercando non esista nemmeno dopo la sostituzione, devi usare un loop.
Per esempio:
var str = 'test aabcbc';
str = str.replace(/abc/g, '');
Al termine, avrai ancora 'test abc'!
Il ciclo più semplice per risolvere questo sarebbe:
var str = 'test aabcbc';
while (str != str.replace(/abc/g, '')){
str.replace(/abc/g, '');
}
Ma questo esegue la sostituzione due volte per ogni ciclo. Forse (a rischio di essere votati in ribasso) che può essere combinato per una forma leggermente più efficiente ma meno leggibile:
var str = 'test aabcbc';
while (str != (str = str.replace(/abc/g, ''))){}
// alert(str); alerts 'test '!
Questo può essere particolarmente utile quando cerchi stringhe duplicate.
Ad esempio, se abbiamo 'a , b' e desideriamo rimuovere tutte le virgole duplicate.
[In tal caso, si potrebbe fare .replace (/, +/g, ','), ma a un certo punto la regex diventa complessa e abbastanza lenta da eseguire il loop.]
Sebbene la gente abbia menzionato l'uso della regex ma c'è un approccio migliore se si vuole sostituire il testo indipendentemente dal caso del testo. Come maiuscole o minuscole. Usa sotto la sintassi
//Consider below example
originalString.replace(/stringToBeReplaced/gi, '');
//Output will be all the occurrences removed irrespective of casing.
Puoi fare riferimento all'esempio dettagliato qui .
La seguente funzione funziona per me:
String.prototype.replaceAllOccurence = function(str1, str2, ignore)
{
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
} ;
Ora chiama le funzioni in questo modo:
"you could be a Project Manager someday, if you work like this.".replaceAllOccurence ("you", "I");
Basta copiare e incollare questo codice nella tua console del browser su TEST.
Puoi semplicemente usare sotto il metodo
/**
* 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);
};
Basta aggiungere /g
document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');
a
// Replace 'hello' string with /hello/g regular expression.
document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi');
/g
significa globale
Ho risolto questo problema con una semplice riga di codice.
str.replace(/Current string/g, "Replaced string");
Controlla esempio su jsfiddle https://jsfiddle.net/pot6whnx/1/
Io uso p per memorizzare il risultato della precedente sostituzione della ricorsione:
function replaceAll(s, m, r, p) {
return s === p || r.contains(m) ? s : replaceAll(s.replace(m, r), m, r, s);
}
Sostituirà tutte le occorrenze nella stringa s finché non sarà possibile:
replaceAll('abbbbb', 'ab', 'a') → 'abbbb' → 'abbb' → 'abb' → 'ab' → 'a'
Per evitare loop infiniti, controllo se la sostituzione r contiene una corrispondenza m :
replaceAll('abbbbb', 'a', 'ab') → 'abbbbb'
La maggior parte delle persone probabilmente lo fa per codificare un URL. Per codificare un URL, non dovresti prendere in considerazione solo gli spazi, ma convertire correttamente l'intera stringa con encodeURI
.
encodeURI("http://www.google.com/a file with spaces.html")
ottenere:
http://www.google.com/a%20file%20with%20spaces.html
In termini di prestazioni relative alle risposte principali questi sono alcuni test online .
Mentre i seguenti sono alcuni test delle prestazioni usando console.time()
(funzionano meglio nella tua console, il tempo è molto breve per essere visto nello snippet)
console.time('split and join');
"javascript-test-find-and-replace-all".split('-').join(' ');
console.timeEnd('split and join')
console.time('regular expression');
"javascript-test-find-and-replace-all".replace(new RegExp('-', 'g'), ' ');
console.timeEnd('regular expression');
console.time('while');
let str1 = "javascript-test-find-and-replace-all";
while (str1.indexOf('-') !== -1) {
str1 = str1.replace('-', ' ');
}
console.timeEnd('while');
La cosa interessante da notare è che se le esegui più volte i risultati sono sempre diversi anche se la soluzione RegExp
sembra la media più veloce e la soluzione loop while
più lenta.
La mia implementazione, molto esplicativa
function replaceAll(string, token, newtoken) {
if(token!=newtoken)
while(string.indexOf(token) > -1) {
string = string.replace(token, newtoken);
}
return string;
}
Per sostituire tutti i tipi di caratteri, prova questo codice:
Suppose we have need to send " and \ in my string, then we will convert it " to \" and \ to \\
Quindi questo metodo risolverà questo problema.
String.prototype.replaceAll = function (find, replace) {
var str = this;
return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};
var message = $('#message').val();
message = message.replaceAll('\\', '\\\\'); /*it will replace \ to \\ */
message = message.replaceAll('"', '\\"'); /*it will replace " to \\"*/
Stavo usando Ajax e ho avuto bisogno di inviare parametri in formato JSON. Quindi il mio metodo è simile a questo:
function sendMessage(source, messageID, toProfileID, userProfileID) {
if (validateTextBox()) {
var message = $('#message').val();
message = message.replaceAll('\\', '\\\\');
message = message.replaceAll('"', '\\"');
$.ajax({
type: "POST",
async: "false",
contentType: "application/json; charset=utf-8",
url: "services/WebService1.asmx/SendMessage",
data: '{"source":"' + source + '","messageID":"' + messageID + '","toProfileID":"' + toProfileID + '","userProfileID":"' + userProfileID + '","message":"' + message + '"}',
dataType: "json",
success: function (data) {
loadMessageAfterSend(toProfileID, userProfileID);
$("#<%=PanelMessageDelete.ClientID%>").hide();
$("#message").val("");
$("#delMessageContainer").show();
$("#msgPanel").show();
},
error: function (result) {
alert("message sending failed");
}
});
}
else {
alert("Please type message in message box.");
$("#message").focus();
}
}
String.prototype.replaceAll = function (find, replace) {
var str = this;
return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};
Nelle mie app, utilizzo una funzione personalizzata che è la più potente per questo scopo, e anche avvolgendo la soluzione split/join
nel caso più semplice, è un po 'più veloce in Chrome 60
and Firefox 54
( JSBEN.CH
) rispetto ad altre soluzioni. Il mio computer esegue Windows 7 64 bits
.
Il vantaggio è che questa funzione personalizzata può gestire molte sostituzioni allo stesso tempo usando stringhe o caratteri, che possono essere una scorciatoia per alcune applicazioni.
Come una soluzione split/join
sopra, la soluzione seguente non ha problemi con i caratteri di escape, diversamente dall'approccio di espressione regolare.
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
}
La documentazione è sotto
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.
Per essere onesti, ho eseguito il benchmark senza test dei parametri.
Ecco il mio set di test, utilizzando 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;
E i risultati:
1 'banana è un Dope frutto raccolto lontano il dover'
2 'banana è un Dope frutto raccolto dor the dover'
3 'banana è un frutto pe raccolto'
4 'bnn s rp frt hrvstd nr th rvr'
5 'banana come rapa fraat harvastad naar tha ravar'
6 'bununu is u ripo frait hurvostod nour tho rivor'
7 falso
8 falso
9 'BANANA IS UN FRUTTO MATURO RACCOLTO VICINO AL FIUME'
10 'BANANA IS A Dope FRUTTA RACCOLTA faR IL DOCCETTO'
Questo può essere ottenuto usando Regex. Poche combinazioni che potrebbero aiutare qualcuno,
var Word = "this,\\ .is*a*test, '.and? / only / 'a \ test?";
var stri = "This is a test and only a test";
Per sostituire tutti i caratteri non alfabetici,
console.log(Word.replace(/([^a-z])/g,' ').replace(/ +/g, ' '));
Result: [this is a test and only a test]
Per sostituire più spazi continui con uno spazio,
console.log(stri.replace(/ +/g,' '));
Result: [This is a test and only a test]
Per sostituire tutti i caratteri *,
console.log(Word.replace(/\*/g,''));
Result: [this,\ .isatest, '.and? / only / 'a test?]
Per sostituire i punti interrogativi (?)
console.log(Word.replace(/\?/g,'#'));
Result: [this,\ .is*a*test, '.and# / only / 'a test#]
Per sostituire le virgolette,
console.log(Word.replace(/'/g,'#'));
Result: [this,\ .is*a*test, #.and? / only / #a test?]
Per sostituire tutti i caratteri,
console.log(Word.replace(/,/g,''));
Result: [this\ .is*a*test '.and? / only / 'a test?]
Per sostituire una parola specifica,
console.log(Word.replace(/test/g,''));
Result: [this,\ .is*a*, '.and? / only / 'a ?]
Per sostituire il back-slash,
console.log(Word.replace(/\\/g,''));
Result: [this, .is*a*test, '.and? / only / 'a test?]
Per sostituire la barra in avanti,
console.log(Word.replace(/\//g,''));
Result: [this,\ .is*a*test, '.and? only 'a test?]
Per sostituire tutti gli spazi,
console.log(Word.replace(/ /g,'#'));
Result: [this,\#.is*a*test,####'.and?#/#only#/#####'a##test?]
Per sostituire i punti,
console.log(Word.replace(/\./g,'#'));
Result: [this,\ #is*a*test, '#and? / only / 'a test?]
function replaceAll(str, find, replace) {
var $r="";
while($r!=str){
$r = str;
str = str.replace(find, replace);
}
return str;
}
Ecco il codice funzionante con prototipo:
String.prototype.replaceAll = function(find, replace) {
var str = this;
return str.replace(new RegExp(find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), 'g'), replace);
};
Per unique valori sostituibili
String.prototype.replaceAll = function(search_array, replacement_array) {
//
var target = this;
//
search_array.forEach(function(substr, index) {
if (typeof replacement_array[index] != "undefined") {
target = target.replace(new RegExp(substr, 'g'), replacement_array[index])
}
});
//
return target;
};
// Use:
var replacedString = "This topic commented on :year. Talking :question.".replaceAll([':year', ':question'], ['2018', 'How to replace all occurrences of a string in JavaScript']);
//
console.log(replacedString);
Metodo 1
Prova ad implementare un'espressione regolare
"Test abc test test abc test test test abc test test abc" .replace (/\abc/g, '');
Metodo 2
Dividi e unisciti. Dividi con abc e unisciti allo spazio vuoto
"Test abc test test abc test test test abc test test abc" .split ("abc"). Join ("")
Se l'utilizzo di una libreria è un'opzione per te, otterrai i vantaggi del testing e del supporto della community che si accompagnano a una funzione di libreria. Ad esempio, il string.js library ha una funzione replaceAll () che fa ciò che stai cercando:
// Include a reference to the string.js library and call it (for example) S.
str = S(str).replaceAll('abc', '').s;
In stringa primo elemento cerca e sostituisci
var str = '[{"id":1,"name":"karthikeyan.a","type":"developer"}]'
var i = str.replace('"[','[').replace(']"',']');
console.log(i,'//first element search and replace')
Nella ricerca globale stringa e sostituire
var str = '[{"id":1,"name":"karthikeyan.a","type":"developer"}]'
var j = str.replace(/\"\[/g,'[').replace(/\]\"/g,']');
console.log(j,'//global search and replace')
Voglio solo condividere la mia soluzione, basata su alcune delle funzionalità delle ultime versioni di JavaScript:
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)
Questo può essere risolto usando le espressioni regolari e la variabile g
, che significa non fermarsi dopo aver trovato la prima corrispondenza. In realtà, le espressioni regolari sono i risparmiatori di vita!
function replaceAll(string, pattern, replacement) {
return string.replace(new RegExp(pattern, "g"), replacement);
}
// or if you want myString.replaceAll("abc", "");
String.prototype.replaceAll = function(pattern, replacement) {
return this.replace(new RegExp(pattern, "g"), replacement);
};
Per sostituire un singolo utilizzo:
var res = str.replace('abc', "");
Per la sostituzione di più volte utilizzare:
var res = str.replace(/abc/g, "");
Questo dovrebbe funzionare.
String.prototype.replaceAll = function (search, replacement){
var str1 = this.replace(search, replacement);
var str2 = this;
while(str1 != str2){
str2 = str1;
str1 = str1.replace(search, replacement);
}
return str1;
}
Esempio:
Console.log("Steve is the best character in minecraft".replaceAll("Steve" ,"Alex"));
Il modo più semplice per farlo senza usare alcuna regex è diviso e unirsi come il codice qui:
var str="Test abc test test abc test test test abc test test abc";
str.split('abc').join('')
Controlla questa risposta potrebbe essere d'aiuto e l'ho usata nel mio progetto.
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 "
Prova questo:
String.prototype.replaceAll = function (sfind, sreplace) {
var str = this;
while (str.indexOf(sfind) > -1) {
str = str.replace(sfind, sreplace);
}
return str;
};
var myName = 'r//i//n//o//l////d';
var myValidName = myName.replace(new RegExp('\//', 'g'), ''); > // rinold
console.log(myValidName);
var myPetName = 'manidog';
var renameManiToJack = myPetName.replace(new RegExp('mani', 'g'), 'jack'); > // jackdog
Tutte le risposte sono accettate, puoi farlo in molti modi. Uno dei trucchi per fare questo è questo.
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);
La soluzione più semplice -
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(" ")
Or Simply -
str = str.split(" ").filter((ele, key) => ele != "abc").join(" ")
La migliore soluzione, al fine di sostituire qualsiasi carattere, usiamo queste funzioni indexOf(), includes(), substring()
per sostituire matched String
con provided String
nella stringa corrente.
String.indexOf()
function è trovare il n
esimo posizione dell'indice di corrispondenza.String.includes()
metodo determina se una stringa può essere trovata all'interno di un'altra stringa, restituendo true o false a seconda dei casi.String.substring()
function è quello di ottenere le parti di String (preceding
, exceding
). Aggiunta la stringa di sostituzione tra queste parti per generare una stringa di restituzione finale.La seguente funzione consente di utilizzare qualsiasi carattere .
dove come RegExp
non permetterà alcuni caratteri speciali come **
e alcuni caratteri devono essere di escape come $
.
String.prototype.replaceAllMatches = function(obj) { // Obj format: { 'matchkey' : 'replaceStr' }
var retStr = this;
for (var x in obj) {
//var matchArray = retStr.match(new RegExp(x, 'ig'));
//for (var i = 0; i < matchArray.length; i++) {
var prevIndex = retStr.indexOf(x); // matchkey = '*', replaceStr = '$*' While loop never ends.
while (retStr.includes(x)) {
retStr = retStr.replaceMatch(x, obj[x], 0);
var replaceIndex = retStr.indexOf(x);
if( replaceIndex < prevIndex + (obj[x]).length) {
break;
} else {
prevIndex = replaceIndex;
}
}
}
return retStr;
};
String.prototype.replaceMatch = function(matchkey, replaceStr, matchIndex) {
var retStr = this, repeatedIndex = 0;
//var matchArray = retStr.match(new RegExp(matchkey, 'ig'));
//for (var x = 0; x < matchArray.length; x++) {
for (var x = 0; (matchkey != null) && (retStr.indexOf(matchkey) > -1); x++) {
if (repeatedIndex == 0 && x == 0) {
repeatedIndex = retStr.indexOf(matchkey);
} else { // matchIndex > 0
repeatedIndex = retStr.indexOf(matchkey, repeatedIndex + 1);
}
if (x == matchIndex) {
retStr = retStr.substring(0, repeatedIndex) + replaceStr + retStr.substring(repeatedIndex + (matchkey.length));
matchkey = null; // To break the loop.
}
}
return retStr;
};
Possiamo anche usare l'oggetto espressione regolare per far corrispondere il testo con un motivo. Le seguenti sono funzioni che saranno oggetto di espressioni regolari.
Otterrai SyntaxError quando utilizzi un patter di espressioni regolari non valido come '**'
.
String.replace()
function viene utilizzato per sostituire la stringa specificata con la stringa specificata.String.match()
function è trovare quante volte viene ripetuta la stringa.RegExp.prototype.test
metodo esegue una ricerca di una corrispondenza tra un'espressione regolare e una stringa specificata. Restituisce vero o falso.String.prototype.replaceAllRegexMatches = function(obj) { // Obj format: { 'matchkey' : 'replaceStr' }
var retStr = this;
for (var x in obj) {
retStr = retStr.replace(new RegExp(x, 'ig'), obj[x]);
}
return retStr;
};
Nota che le espressioni regolari sono scritte senza virgolette.
Esempi da utilizzare sopra le funzioni:
var str = "yash yas $dfdas.**";
console.log('String : ', str);
// No need to escape any special Character
console.log('Index Matched replace : ', str.replaceMatch('as', '*', 2) );
console.log('Index Matched replace : ', str.replaceMatch('y', '~', 1) );
console.log('All Matched replace : ', str.replaceAllMatches({'as' : '**', 'y':'Y', '$':'-'}));
console.log('All Matched replace : ', str.replaceAllMatches({'**' : '~~', '$':'&$&', '&':'%', '~':'>'}));
// You need to escape some special Characters
console.log('REGEX All Matched replace : ', str.replaceAllRegexMatches({'as' : '**', 'y':'Y', '\\$':'-'}));
Risultato:
String : yash yas $dfdas.**
Index Matched replace : yash yas $dfd*.**
Index Matched replace : yash ~as $dfdas.**
All Matched replace : Y**h Y** -dfd**.**
All Matched replace : yash yas %$%dfdas.>>
REGEX All Matched replace : Y**h Y** -dfd**.**