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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:19:19  来源:igfitidea点击:

JavaScript - check if string starts with

javascript

提问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

data.substring(0, input.length) === input

See following sample code

请参阅以下示例代码

var data = "/hello";
var input = "/";
if(data.substring(0, input.length) === input)
    alert("slash found");
else 
    alert("slash not found");

Fiddle

小提琴

回答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) === '/')