如何知道字符串在javascript中以特定字符开头/结尾?

Rac*_*hel 1 javascript string validation

 var file = "{employee}";
 var imgFile = "cancel.json";

  if(file starts with '{' and file ends with '}' ){
     alert("invalid");
  }
  if(imgFile ends with '.json'){
    alert("invalid");
  }
Run Code Online (Sandbox Code Playgroud)
  • 如何使用javascript验证字符串的开始和结束字符?
  • 在"文件"中,字符串不应以"{"开头,不应以"}"结尾
  • 在"imgFile"中,字符串不应以'.json'结尾
  • match()是否有效或应该使用indexOf()

Ber*_*rgi 6

match()是否有效或应该使用indexOf()

都不是.两者都有效,但都搜索整个字符串.在相关位置提取子字符串并将其与您期望的子字符串进行比较会更有效:

if (file.charAt(0) == '{' && file.charAt(file.length-1) == '}') alert('invalid');
// or:                       file.slice(-1) == '}'
if (imgFile.slice(-5) == '.json') alert('invalid');
Run Code Online (Sandbox Code Playgroud)

当然,您也可以使用正则表达式,使用智能正则表达式引擎,它也应该是高效的(并且您的代码更简洁):

if (/^\{[\S\s]*}$/.test(file)) alert('invalid');
if (/\.json$/.test(imgFile)) alert('invalid');
Run Code Online (Sandbox Code Playgroud)