Sam
0
Q:

javascript replaceall

const p = 'dog dog cat rat';

const regex = /dog/gi;

console.log(p.replace(regex, 'cow'));
//if pattern is regular expression all matches will be replaced
//output: "cow cow cat rat"
25
var res = str.replace("find", "replace");
25
let startText = "Yes, I said yes, it is, yes."

// Replace with no modifiers
let newText = startText.replace("yes", "no")
console.log(newText)  // "Yes, I said no, it is, yes."

// Replace with 'g'-global modifier
newText = startText.replace(/yes/g, "no")
console.log(newText)  // "Yes, I said no, it is, no."

// Replace with modifiers 'g'-global and 'i'-case insensitive
newText = startText.replace(/yes/gi, "no")
console.log(newText)  // "no, I said no, it is, no."
9

var str = "Mr Blue has a blue house and a blue car";

var res = str.replace(/blue/g, "red");
 
12
function replaceAll(str, find, replace) {
    var escapedFind=find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    return str.replace(new RegExp(escapedFind, 'g'), replace);
}
//usage example
var sentence="How many shots did Bill take last night? That Bill is so crazy!";
var blameSusan=replaceAll(sentence,"Bill","Susan"); 
12
let a = 'a a a a aaaa aa a a';
a.replace(/aa/g, 'bb');
// => "a a a a bbbb bb a a"
1
let string = 'soandso, my name is soandso';

let replaced = string.replace(/soandso/gi, 'Dylan');

console.log(replaced); //Dylan, my name is Dylan
9

var str = "Visit Microsoft!";

var res = str.replace("Microsoft", "W3Schools");
 
8
str.split(search).join(replacement);
7
let re = /apples/gi; 
let str = "Apples are round, and apples are juicy.";
let newstr = str.replace(re, "oranges"); 
console.log(newstr)

output:

"oranges are round, and oranges are juicy."
0
//as of August 2020, not supported on older browsers
str.replaceAll("abc","def")
0

New to Communities?

Join the community