【问题标题】:Count certain words in string javascript [closed]计算字符串javascript中的某些单词[关闭]
【发布时间】:2014-01-02 01:23:04
【问题描述】:

我正在寻找一种方法来计算字符串中的某些单词。

$string = "How are you doing today? You are such a nice person!";

我的目标是计算 $string 变量中有多少个“是”。

期望结果:2

【问题讨论】:

  • 诸如此类的词怎么样; Bare、Care、Dare、Fare.. 他们算数吗?
  • "How are you doing today? You are such a nice person!".match(/\bare\b/g).length
  • @megawac:这应该是答案
  • 这是区分大小写还是不区分大小写?

标签: javascript jquery string var


【解决方案1】:

试试这个:

var count =  yourString.match(/\bare\b/g); 
count = count? count.length : 0;  //checking if there are matches or not.
console.log(count);

【讨论】:

  • 我认为|! 是不必要的(一个句子也可以和其他符号一起使用,例如We are?),\b 就足够了。
  • @IngoBürk 是的,你是对的。这只是你在下面的 cmets 中提到的一个测试 :) 无论如何你都可以这样做/\bare(\b|[!?])/g
【解决方案2】:
var string = "are you bare footed?";
console.log(string.split(/\bare\b/).length - 1);

【讨论】:

  • 句子Are you home? You are such a nice person! 输出:1。
  • @ErikPhilips 我相信他没有提到任何关于区分大小写的事情。
  • +1 我也喜欢在适用时不使用正则表达式。
  • 不幸的是,无论是这个还是一个简单的正则表达式都不行。示例:Foo are baz barefoot. We totally are!。它应该给出两个匹配项。你的方法会给三个。在单词周围添加空格也不行。
  • 当有像fare aware 这样的单词包含“are”时,如果不使用正则表达式,这是不可能的。
【解决方案3】:
var str = "How are you doing today? You are such a nice person!";
var matchs;
matchs = str.match(/are/gi);
alert(matchs.length);

试试这个javascript匹配它返回匹配字符串为数组格式,length方法返回多少数组索引匹配。

【讨论】:

    【解决方案4】:

    试试下面。

        var temp = "How are you doing today? You are such a nice person!.";
    
    var count = countOcurrences(temp,"are");  
    
    alert(count);
    
    function countOcurrences(str, value){
       var regExp = new RegExp(value, "gi");
       return str.match(regExp) ? str.match(regExp).length : 0;  
    }
    

    【讨论】:

      【解决方案5】:

      试试这个:

      $string = "How are you doing today? You are such a nice person!";
      
      var count = $string.match(/are/g);  
      
      alert(count.length);
      

      【讨论】:

        【解决方案6】:

        试试这个:

        var string = "How are you doing today? You are such a nice person!";
        var num = string.match(/are/g).length;
        alert(num);
        

        这里是Demo

        【讨论】:

          【解决方案7】:

          你也可以试试这样的:

          var temp = "How are you doing today? You are such  a nice person!.";
          var arr = [];
          for(var i = 0;i< temp.split(' ').length; i++)
          {   
              if(temp.split(' ')[i] === "are"){
               arr.push(temp.split(' '));
          
               }
          
          }
          alert(arr.length)
          

          【讨论】:

            猜你喜欢
            • 2013-02-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-09-26
            • 2021-07-30
            • 2023-03-21
            相关资源
            最近更新 更多