代码之家  ›  专栏  ›  技术社区  ›  Sandeep Thomas

如何查找字符串中存在的任何特定字符

  •  0
  • Sandeep Thomas  · 技术社区  · 8 年前

    现在我用数组和循环来做。但老实说,我觉得这不是一个好方法。那么,没有数组或循环有什么最简单的方法吗?

    var special = ['$', '%', '@'];
    var mystring = ' using it to replace VLOOKUP entirely.$ But there are still a few lookups that you are not sure how to perform. Most importantly, you would like to be able to look up a value based on multiple criteria within separate columns.';
    var exists = false;
    $.each(special, function(index, item) {
      if (mystring.indexOf(item) >= 0) {
        exists = true;
      }
    });
    console.info(exists);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    3 回复  |  直到 8 年前
        1
  •  1
  •   Bhargav Chudasama    8 年前

    尝试使用 regex

    var patt = /[$%@]/;
    console.log(patt.test("using it to replace VLOOKUP entirely.$ But there are still a few lookups that you are not sure how to perform. Most importantly, you would like to be able to look up a value based on multiple criteria within separate columns."));
        2
  •  1
  •   Keith    8 年前

    [x] 在正则表达式中,仅用于单个字符。

    replace ,它将查找字符串中包含“r,e,p,l,a,c”的任何内容。

    Is there a RegExp.escape function in Javascript? 我在字符串中找到了一个更一般的结果。

    你当然问了 given characters in a string ,所以对于任何在上面找到这篇文章的人来说,这更像是一个补充答案。当我们看一个字符串数组的原始问题时,人们可能很容易认为这就是可以传递给正则表达式的内容。IOW:你的问题不是我怎么知道$,%,@是否存在于字符串中。

    var mystring = ' using it to replace VLOOKUP entirely.$ But there are still a few lookups that you are not sure how to perform. Most importantly, you would like to be able to look up a value based on multiple criteria within separate columns.';
    
    function makeStrSearchRegEx(findlist) {
      return new RegExp('('+findlist.map(
      s=>s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).join('|')+')');
    }
    
    var re = makeStrSearchRegEx(['$', '%', '@', 'VLOOKUP']);
    
    
    console.log(re.test(mystring));  //true
    console.log(re.test('...VLOOKUP..')); //true
    console.log(re.test('...LOOKUP..'));  //false
        3
  •  0
  •   Dmytro Medvid    8 年前

    最好的方法是使用正则表达式。你可以了解更多 here

    在你的情况下,你应该这样做:

    const specialCharacters = /[$%@]/;
    const myString = ' using it to replace VLOOKUP entirely.$ But there are still a few lookups that you are not sure how to perform. Most importantly, you would like to be able to look up a value based on multiple criteria within separate columns.';
    if(specialCharacters.test(myString)) {
       console.info("Exists...");
    }