Trying to make sure no one put a space in the username on sign up, I got the html tags to removed but not spaces.
Javascript:
$("#user").keypress(function (evt) {
if (isValid(String.fromCharCode(evt.which)))
return false;
});
function isValid(str) {
return /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
function stripspaces(input) {
input.value = input.value.replace(/\s/gi, "");
return true;
}
HTML:
Username: <input type="text" id="user"><br/>
You can see it here. http://jsfiddle.net/QshDd/63/
You can try with (each space character is being replaced, character by character, with the empty string):
str = str.replace(/\s/g, '');
or (each contiguous string of space characters is being replaced with the empty string by the "+" character):
str = str.replace(/\s+/g, '');
Ciao!
You need to return the input value with the spaces removed:
function stripspaces(input)
{
return input.value.replace(/\s/gi,"");
}
The way you had it written the function just returned true
regardless. Also, it seems you weren't calling the function (admittedly from only a quick read).
Although, it's probably easier to simply add \\s
(a regular expression special character for white-space characters) to the characters to replace, giving:
function isValid(str) {
return /[~`!#$%\^&*+=\-\[\]\\';,/\s{}|\\":<>\?]/g.test(str);
}
References:
尝试这个,
input.value.replace(/\n/g," ").replace( /<.*?>/g, "" );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.