簡體   English   中英

刪除空格和HTML標簽

[英]Remove Spaces and HTML Tags

為了確保沒有人在用戶名上輸入空格,我將html標記刪除,但沒有空格。

使用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/>

在這里你可以看到它。 http://jsfiddle.net/QshDd/63/

您可以嘗試(每個空格字符都被替換為空字符,用空字符串替換):

str = str.replace(/\s/g, '');

或(每個連續的空格字符都由空字符串替換為“ +”字符):

str = str.replace(/\s+/g, '');

再見!

您需要返回除去空格的輸入值:

function stripspaces(input)
{
  return input.value.replace(/\s/gi,"");
}

無論如何,編寫函數的方式都返回true 另外,似乎您沒有在調用該函數(僅通過快速閱讀即可)。

雖然,將\\s (用於空白字符的正則表達式特殊字符)簡單地添加到要替換的字符中可能會更容易,從而得到:

function isValid(str) {
    return /[~`!#$%\^&*+=\-\[\]\\';,/\s{}|\\":<>\?]/g.test(str);
}

JS小提琴演示

參考文獻:

嘗試這個,

input.value.replace(/\n/g," ").replace( /<.*?>/g, "" );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM