Answers for "js replaceall vs replace"

21

replaceAll alternative with string value javascript

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");
Posted by: Guest on July-22-2019
0

replace vs replaceall

const source = "abcdefabcdef";
const str1 = "abc", str2 = "xyz";
const reg1 = /abc/g, reg2 = "xyz";

//Case 1 : When we want to replace a string by another
console.log(source.split(str1).join(str2));
console.log(source.replace(new RegExp(str1,"g"),str2));
//versus
console.log(source.replaceAll(str1,str2));

//Case 2 : When we want to use a regular expression
console.log(source.replace(reg1,reg2));
//versus
console.log(source.replaceAll(reg1,reg2));

//Result = "xyzdefxyzdef"
Posted by: Guest on July-24-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language