admin管理员组文章数量:1353256
I am getting value from a text field. I want to show an alert message if a special character, say % doesn't appear at the end of entered input.
Usecases:
- ab%C - show alert
- %abc- show alert
- a%bc- show alert
- abc%- ok
The regex i came up so far is this.
var txtVal = document.getElementById("sometextField").value;
if (!/^[%]/.test(txtVal))
alert("% only allowed at the end.");
Please help. Thanks
I am getting value from a text field. I want to show an alert message if a special character, say % doesn't appear at the end of entered input.
Usecases:
- ab%C - show alert
- %abc- show alert
- a%bc- show alert
- abc%- ok
The regex i came up so far is this.
var txtVal = document.getElementById("sometextField").value;
if (!/^[%]/.test(txtVal))
alert("% only allowed at the end.");
Please help. Thanks
Share Improve this question edited Jan 2, 2012 at 1:44 Nomad asked Jan 2, 2012 at 1:43 NomadNomad 1,10012 gold badges29 silver badges42 bronze badges 3-
What if
%
is not present in the string? – Sergio Tulentsev Commented Jan 2, 2012 at 1:45 - @Sergio Tulentsev. The string wont have it. It's user entered value which will contain the %, meaning user will enter it abcde%f etc. – Nomad Commented Jan 2, 2012 at 1:47
- are you saying that we can assume that '%' always exists in the string, and we should check if it's the last symbol or not? – Sergio Tulentsev Commented Jan 2, 2012 at 1:49
4 Answers
Reset to default 5No need for a regex. indexOf will find the first occurrence of a character, so just check it it's at the end:
if(str.indexOf('%') != str.length -1) {
// alert something
}
2020 edit, use string.endsWith()
You don't need regex to check for this at all.
var foo = "abcd%ef";
var lastchar = foo[foo.length - 1];
if (lastchar != '%') {
alert("hello");
}
http://jsfiddle/cwu4S/
if (/%(?!$)/.test(txtVal))
alert("% only allowed at the end.");
or to make it more readable by not using a RegExp
:
var pct = txtVal.indexOf('%');
if (0 <= pct && pct < txtVal.length - 1) {
alert("% only allowed at the end.");
}
Would this work?
if (txtVal[txtVal.length-1]=='%') {
alert("It's there");
}
else {
alert("It's not there");
}
本文标签: regexjavascript check for a special character at the end of a stringStack Overflow
版权声明:本文标题:regex - javascript check for a special character at the end of a string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743882012a2555371.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论