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

时间:2013-05-23 08:24:47

标签: 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");
  }
  • 如何使用javascript验证字符串的开始和结束字符?
  • 在“file”中,字符串不应以“{”开头,不应以“}”结尾
  • 在“imgFile”中,字符串不应以'.json'结尾
  • match()是否有效或应该使用indexOf()

7 个答案:

答案 0 :(得分: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');

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

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

答案 1 :(得分:3)

if (str.charAt(0) == 'a' && str.charAt(str.length-1) == 'b') {
    //The str starts with a and ends with b
}

未经测试,但应该有效

答案 2 :(得分:1)

 /^\{.*\}$/.test (str)

将从str开始返回{,并以}结尾

答案 3 :(得分:0)

你可以使用javascript startswith()和endswith()

    function strStartsWith(str, prefix) {
    return str.indexOf(prefix) === 0;
}
function strEndsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
or
function strEndsWith(str, suffix) {
var re=new RegExp("."+suffix+"$","i");
if(re.test(str)) alert("invalid file");

}

或者您也可以这样使用它:

String.prototype.startsWith = function (str){
return this.slice(0, str.length) == str;
};
 and

String.prototype.endsWith = function (str){
return this.slice(-str.length) == str;
};

答案 4 :(得分:0)

  

在“file”中,字符串不应以“{”开头,不应以“}”结尾

    if (file.charAt(0) == '{' || file.charAt(file.length - 1) == '}') {
        throw 'invalid file';
    }
  

在“imgFile”中,字符串不应以'.json'结尾

    if (imgFile.lastIndexOf('.json') === imgFile.length - 5) {
        throw 'invalid imgFile';
    }

答案 5 :(得分:0)

file.indexOf("{") == 0 && file.lastIndexOf("}") == file.length-1

答案 6 :(得分:0)

在字符串验证方面你有很多选择,你可以使用正则表达式。不同的字符串方法也可以为你做...

但您的问题可以尝试以下方法:

if(file.indexOf('{') == 0 && file.indexOf('}') == file.length - 1) 
        alert('invalid');

对于第二部分,您最有可能寻找文件的扩展名,以便您可以使用以下内容:

if(imgFile.split('.').pop() == "json")
    alert('invalid');   

希望这会有所帮助......