Created
May 16, 2019 05:41
-
-
Save LI-NA/98149620fe40daa225bc0d4cce3cf6e7 to your computer and use it in GitHub Desktop.
Javascript single line replace all function using RegExp.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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