Last active
January 26, 2018 15:00
-
-
Save coolreader18/c34c08aacc0c106a2ad72e474ec5d289 to your computer and use it in GitHub Desktop.
Automatically replace text in input fields
This file contains 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
/** | |
* Replaces text automatically in an HTML element that has a value attribute and an input event, such as <input type=text> or <textarea></textarea> | |
* @param {EventTarget} element The element that you wish to autoreplace text in. | |
* @param {Array} arr The array of options arrays. Each array element should be an array, with its first element being a string to input, and the second being a RegExp or array of RegExps that it will replace | |
* @example <caption>Replaces any match of the regex's /Hello/gi or /example/g with the string "World" in the element with id=input</caption> | |
* autoReplace(document.getElementById("input"), [ | |
* ["World", [/Hello/gi, /example/g]] | |
* ]); | |
*/ | |
function autoReplace(element, arr) { | |
element.addEventListener("input", e => { | |
var ct = e.currentTarget, | |
val = ct.value, | |
value = v => { | |
ct.value = v | |
}; | |
arr.forEach(([str, regs]) => { | |
if (Array.isArray(regs)) { | |
regs.forEach(check) | |
} else { | |
check(regs) | |
} | |
function check(regex) { | |
if (val.match(regex)) { | |
value(val.replace(regex, str)) | |
} | |
} | |
}) | |
}) | |
} | |
try{export default autoReplace;}catch(e){try{module.exports=autoReplace}catch(r){}}; |
This file contains 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
{ | |
"name": "auto-replace-text", | |
"version": "1.0.0", | |
"author": "coolreader18", | |
"main": "auto-replace.js", | |
"repository": "gist:coolreader18/c34c08aacc0c106a2ad72e474ec5d289", | |
"license": "MIT" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment