Javascript how many characters replaced in a regex?
- by macca1
I am sanitizing an input field and manually getting and setting the caret position in the process. With some abstraction, here's the basic idea:
<input type="text" onkeyup"check(this)">
And javascript...
function check(element) {
var charPosition = getCaretPosition(element);
$(element).val( sanitize( $(element).val() ) );
setCaretPosition(element, charPosition);
}
function sanitize(s) {
return s.replace(/[^a-zA-Z0-9\s]/g, '');
}
This is working fine except when a character does actually get sanitized, my caret position is off by one. Basically I'd like a way to see if the sanitize function has actually replaced a character (and at what index) so then I can adjust the charPosition if necessary. Any ideas?