ReplaceAll in Javascirpt

JavaScript Sep 9, 2015

Usecase:

To Replace all occurrences of character/sub-string in a string using javascript.

Note: There is nothing called ReplaceAll in javascript, so this would be workaround for that

Javascript Codesnippet

function escapeRegExp(string) {
    return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
function replaceAll(string, find, replace) {
  return string.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

// invoke function as
replaceAll('testing & with & and &', '&', '%26')

Output

Phanindra Mangipudi

Salesforce, Lightning Web Componets, Node.Js, Angular 2+, Bootstrap