检查字符串是否以多个字符结尾 [英] Check if string ends with any of multiple characters

查看:76
本文介绍了检查字符串是否以多个字符结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何检查字符串是否以多个字符中的任何一个结尾?目前,此代码返回false,即使字符串以问号结尾。如果字符串以句点,感叹号或问号结束,则正常工作的代码将返回true,如果其最后一个字符是其他任何字符,则返回false。



显然我可以独立检查这些条件但是假设我有一个很长的清单,肯定有更好的方法吗?



< pre class =snippet-code-js lang-js prettyprint-override> function myFunction(){var str =Hello?; var n = str.endsWith(。,!,?); document.getElementById(demo)。innerHTML = n;}

 < button onclick =myFunction()>试一试< / button>< p id =demo>< / p>  

解决方案

endsWith 只是没有多个字符串进行测试。您可以定义它们的数组并使用 endsWith 检查每个值:

  function endsWithAny(suffixes,string){
return suffixes.some(function(suffix){
return string.endsWith(suffix);
});
}

函数myFunction(){
var str =Hello?;
var n = endsWithAny([。,!,?],str);
document.getElementById(demo)。innerHTML = n;
}

或者使用正则表达式进行一次性付款:

  var n = /[.!?]$/.test(str); 


How would I check to see if a string ends in any one of multiple characters? Currently this code returns false, even though the string ends in a question mark.The properly working code would return true if the string ends in either a period, exclamation mark, or question mark, and return false if its last character is anything else.

Obviously I could check these conditions independently but suppose I had a very long list, surely there is a better way?

function myFunction() {
    var str = "Hello?";
    var n = str.endsWith(".", "!", "?");
    document.getElementById("demo").innerHTML = n;
}

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

解决方案

endsWith just doesn’t take multiple strings to test. You could define an array of them and check each value with endsWith:

function endsWithAny(suffixes, string) {
    return suffixes.some(function (suffix) {
        return string.endsWith(suffix);
    });
}

function myFunction() {
    var str = "Hello?";
    var n = endsWithAny([".", "!", "?"], str);
    document.getElementById("demo").innerHTML = n;
}

Or use a regular expression for a one-off:

var n = /[.!?]$/.test(str);

这篇关于检查字符串是否以多个字符结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆