Skip to content

Instantly share code, notes, and snippets.

@LI-NA
Created May 16, 2019 05:41
Show Gist options
  • Save LI-NA/98149620fe40daa225bc0d4cce3cf6e7 to your computer and use it in GitHub Desktop.
Save LI-NA/98149620fe40daa225bc0d4cce3cf6e7 to your computer and use it in GitHub Desktop.
Javascript single line replace all function using RegExp.
/**
* Replace every string to string from string. lol
* @param {string} target target string
* @param {string} from search value
* @param {string} to replace value
*/
const replaceAll = (target, from, to) => target.replace(new RegExp(from.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), to)
// it is same as this.
const replaceAllMultiLine = (target, from, to) => {
// make from to Regex safe string. It will replace . to \.
from = from.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
// Create new regex using from with g flag.
let reg = new RegExp(from, "g")
// replace it and return it!
return target.replace(reg, to)
}
// Test it. It will be return return c..b..c..b..
replaceAll("a..b..a..b..", "a..", "c..")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment