ReplaceAll in Javascirpt

ReplaceAll in Javascirpt

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

Subscribe to Phanindra Mangipudi

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe