简体   繁体   English

javascript在字符串开头检查特殊字符

[英]javascript check for a special character at the beginning a string

I am trying to get a value from input field. 我试图从输入字段中获取一个值。

I want to check if the string has % or * at the beginning of the string then show an alert. 我想检查字符串的开头是否有%或*,然后显示警报。

if (/^[%*]/.test(document.getElementById("yourelementid").value))
   alert("Where can I find a JavaScript tutorial?");

By way of explanation: the regular expression /^[%*]/ means: 作为解释:正则表达式/^[%*]/表示:

^       match the beginning of the string, followed immediately by
[%*]    any one of the characters inside the brackets

Testing the entered value against that regex will return true or false. 针对该正则表达式测试输入的值将返回true或false。

getElementById(ID).value.charAt(0); getElementById(ID).value.charAt(0);

I'm sure you can figure out the rest. 我相信您能弄清楚其余的一切。 Please do some research first as things like this should be really easy to find by googling it. 请先做一些研究,因为通过谷歌搜索这样的事情应该很容易找到。

You can do that by using the indexOf method of strings. 您可以使用字符串的indexOf方法来实现。

var s = "%kdjfkjdf";
if (s.indexOf("%") == 0 || s.indexOf("*") == 0)
{
   // do something
}

You can also use regular expressions too as pointed out in @nnnnnn's answer. 您也可以使用@nnnnnn的答案中指出的正则表达式。

Refer to below link. 请参考下面的链接。

javascript pattern matching javascript模式匹配

You can use the substring method, for example: 您可以使用substring方法,例如:

data.substring(0, 1) === '%'

if(data.substring(0, 1) === '%' || data.substring(0, 1) === '*')
{ 
   alert("Not allowed"); 
}

or you can try the regex way. 或者您可以尝试使用正则表达式。

var str="%*hkfhkasdfjlkjasdfjkdas";

if(str.indexOf("%") === 0|| str.indexOf("*") === 0){
alert("true");
}
else{
alert("false");
}

please check fiddle here. 请在这里检查小提琴。 http://jsfiddle.net/RPxMS/ http://jsfiddle.net/RPxMS/

you can also use prototype plugin for javascript which contains method startWith . 您也可以使用包含方法startWith javascript prototype插件。

if(str.startWith("%"))
{
// do
}

check the details in the link: click here 检查链接中的详细信息: 单击此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM