2012-01-02 101 views
2

我從文本字段獲取值。如果輸入的輸入末尾沒有出現特殊字符(例如%),我想顯示警告消息。JavaScript檢查字符串末尾的特殊字符

Usecases:

  1. AB%C - 顯示警報
  2. %ABC-顯示警報
  3. 一%BC-顯示警報
  4. ABC% - 確定

正則表達式我到目前爲止是這樣的。

var txtVal = document.getElementById("sometextField").value; 

if (!/^[%]/.test(txtVal)) 
    alert("% only allowed at the end."); 

請幫忙。 感謝

+0

那麼,它不工作? – 2012-01-02 01:44:48

+0

如果字符串中不存在'%',該怎麼辦? – 2012-01-02 01:45:22

+0

@Sergio Tulentsev。該字符串不會有它。它是包含%的用戶輸入值,意味着用戶將輸入它爲abcde%f等 – Nomad 2012-01-02 01:47:33

回答

3

無需使用正則表達式。的indexOf會發現一個字符的第一次出現,所以只檢查它的結尾:

if(str.indexOf('%') != str.length -1) { 
    // alert something 
} 
+0

感謝您的回答,它似乎在工作。 http://jsfiddle.net/pQzvd/ – Nomad 2012-01-02 02:07:10

+0

「它似乎在工作」。你明白它爲什麼有效嗎? – 2012-01-03 01:31:45

+0

是的,我喜歡。謝謝。 – Nomad 2012-01-04 22:02:12

2
if (/%(?!$)/.test(txtVal)) 
    alert("% only allowed at the end."); 

或使不使用一個RegExp它更易讀:

var pct = txtVal.indexOf('%'); 
if (0 <= pct && pct < txtVal.length - 1) { 
    alert("% only allowed at the end."); 
} 
+0

感謝您的回答和幫助,正則表達式似乎是工作,但不是第二個。 http://jsfiddle.net/ZHpDN/2/ – Nomad 2012-01-02 01:57:56

+0

@Nomad,那真是愚蠢。修正了第二個。 – 2012-01-02 15:58:24

+0

感謝您的更新,非常感謝您的幫助和時間。 – Nomad 2012-01-04 22:02:37

2

你不需要正則表達式來檢查這個在所有。

var foo = "abcd%ef"; 
var lastchar = foo[foo.length - 1]; 
if (lastchar != '%') { 
    alert("hello"); 
} 

http://jsfiddle.net/cwu4S/

+0

感謝您的回答,但您的回答似乎不起作用。 http://jsfiddle.net/4tzmR/1/ – Nomad 2012-01-02 02:01:28

+0

我在這個例子中有兩個語法錯誤。有一個額外的右括號和缺少的分號。 http://jsfiddle.net/4tzmR/3/ – mrtsherman 2012-01-02 02:07:08

1

將這項工作?

if (txtVal[txtVal.length-1]=='%') { 
    alert("It's there"); 
} 
else { 
    alert("It's not there"); 
} 
+0

感謝您的回答,它似乎工作。 – Nomad 2012-01-02 02:08:31

相關問題