JavaScript - 检查字符串是否以
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15310917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript - check if string starts with
提问by Alosyius
I am trying to check if a string starts with the character: /
我正在尝试检查字符串是否以字符开头:/
How can i accomplish this?
我怎样才能做到这一点?
回答by Justin Niessner
if(someString.indexOf('/') === 0) {
}
回答by 0x499602D2
Characters of a string can be accessed through the subscript operator []
.
可以通过下标运算符访问字符串的字符[]
。
if (string[0] == '/') {
}
[0]
means the first character in the string as indexing is 0-based in JS. The above can also be done with regular expressions.
[0]
表示字符串中的第一个字符,因为索引在 JS 中是基于 0 的。以上也可以用正则表达式来完成。
回答by KooiInc
Alternative to String.indexOf
: /^\//.test(yourString)
替代String.indexOf
:/^\//.test(yourString)
回答by Umair Saleem
回答by MackieeE
<script>
function checkvalidate( CheckString ) {
if ( CheckString.indexOf("/") == 0 )
alert ("this string has a /!");
}
</script>
<input type="text" id="textinput" value="" />
<input type="button" onclick="checkvalidate( document.getElementById('textinput').value );" value="Checkme" />
回答by Amrendra
var str = "abcd";
if (str.charAt(0) === '/')