简体   繁体   English

如何使后缀函数不区分大小写?

[英]How do I make suffix function case-insensitive?

I'd like to make the following code case-insensitive.我想让以下代码不区分大小写。 If I test it out with如果我测试它

isSuffix("Albatross", "Ross")

it returns false, but if I try它返回false,但如果我尝试

isSuffix("Albatross", "ross")

it returns true.它返回真。

How do I make it case-insensitive?我如何使它不区分大小写?

function isSuffix(str, suffix) {
  if (str.substring(str.length - suffix.length) == suffix) {
    return true;

  return false;
}

You can do this with regular expressions:您可以使用正则表达式执行此操作:

function isSuffix(str, suffix) {
    var regSuffix = new RegExp(suffix + '$', 'i');
    if ( regSuffix.test(str) ) {
        return true;
    }
    return false;
}

Just use the toLowerCase function.只需使用toLowerCase函数。

function isSuffix(str, suffix) {
    str = str.toLowerCase();
    if (str.substring(str.length - suffix.length) == suffix.toLowerCase()) {
        return true;
    }
    return false;
}

You can use String.toLowerCase()您可以使用String.toLowerCase()

function isSuffix(str, suffix) {
if (str.substring(str.length - suffix.length).toLowerCase() == suffix.toLowerCase())
    return true;
return false;
}

alert(isSuffix("Albatross", "Ross"))

You could use a regular expression, too, but this is closer to your original code.您也可以使用正则表达式,但这更接近您的原始代码。

Change your code to this (which makes use of .toLowerCase()将您的代码更改为此(使用.toLowerCase()

function isSuffix(str, suffix) {
    return (str.substring(str.length - suffix.length).toLowerCase() == suffix.toLowerCase());
}

Unless you can use case insensitive regular expression match with "i" (when suffix is either just text or cost of escaping worth it) you have to convert strings to lower case first before searching.除非您可以使用与“i”匹配的不区分大小写的正则表达式(当后缀只是文本或转义成本时),您必须在搜索之前先将字符串转换为小写。 Depending on your operations per-converting one or both to lower case may give better performance if you need to perform a lot of searches.如果您需要执行大量搜索,根据您的操作,将一个或两个都转换为小写可能会提供更好的性能。

Creating new string to simply check if suffix matches could also be wasteful.创建新字符串来简单地检查后缀是否匹配也可能是浪费。 For ancient browsers you can use lastIndexOf after converting string to lower case with toLowerCase .对于古老的浏览器,您可以在使用toLowerCase将字符串转换为小写后使用lastIndexOf

For more modern JavaScript code (current versions of browsers/NodeJS) use endsWith (the link also includes polyfill):对于更现代的 JavaScript 代码(当前版本的浏览器/ NodeJS ),请使用endsWith (该链接还包括polyfill ):

function isSuffix(str, suffix) {
   return (str.toLowerCase().endsWith(suffix.toLowerCase());
}    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM