How do you replace many characters in a regex?
Posted
by macca1
on Stack Overflow
See other posts from Stack Overflow
or by macca1
Published on 2010-03-17T20:33:54Z
Indexed on
2010/03/17
21:31 UTC
Read the original article
Hit count: 248
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?
© Stack Overflow or respective owner