【问题标题】:trying to find words that begin with a试图找到以 a 开头的单词
【发布时间】:2019-07-23 01:32:41
【问题描述】:

我正在编写一些代码来查找以字母“a”开头的段落中的单词。我想知道是否有一个快捷方式可以放在变量中。我确实知道 startsWith() 函数,但这不适用于我想要做的事情。这是我到目前为止所拥有的。我正在尝试使用 match 方法和 .innerText 来阅读段落。

function processText() {
  var totalNumberOfWords = document.getElementById('p')
  var wordsBegginingWithA = 0;
  var wordsEndingWithW = 0;
  var wordsFourLettersLong = 0;
  var hyphenatedWords = 0;

}
<p><button onClick="processText();">Process</button></p>
<p id="data"></p>
<p>The thousand injuries of Fortunato I had borne as I best could; but when he ventured upon insult, I vowed revenge. You, who so well know the nature of my soul, will not suppose, however, that I gave utterance to a threat.
  <span style='font-style:italic;'>At
            length</span> I would be avenged; this was a point definitely settled--but the very definitiveness with which it was resolved precluded the idea of risk. I must not only punish, but punish with impunity. A wrong is unredressed when retribution
  overtakes its redresser. It is equally unredressed when the avenger fails to make himself felt as such to him who has done the wrong.</p>

【问题讨论】:

  • 我们需要一些代码来帮助您...
  • 改变了它。如果您需要更多代码,请 Lmk
  • 能否提供相关段落
  • 很长,大约300行。我可以给出我已链接到该功能的段落和按钮之一吗?
  • 只给出包含所有需要内容的段落的一小部分。

标签: javascript html


【解决方案1】:

您可以使用: [variablename].match(/(?&lt;!\w)a\w*/ig)!=null? a.match(/(?&lt;!\w)a\w*/ig).length:0; 检测以什么字母开头的单词(例如它是a)。

并且: [variablename].match(/\S+/g)!=null? a.match(/\S+/g).length:0; 检测字数。

function processText() {
    var a = document.getElementById('p').innerText;
    var b = a.match(/(?<!\w)a\w*/ig)!=null? a.match(/(?<!\w)a\w*/ig).length:0;
    var word= a.match(/\S+/g)!=null? a.match(/\S+/g).length:0; 
    console.log('Text: ',a,'\nA starting word: ', b, '\nWord count: ',word);

}

processText();
&lt;span id="p"&gt;Apple is super delicious. An ant is as good as my cat which favors a pear than fish. I'm going to test them all at once.&lt;/span&gt;

解释:.match 将返回与给定表达式匹配的所有值。 请注意,我还使用conditional (ternary) operator 来检测如果没有返回匹配项,Regex 是否会返回空值。如果它返回 null,那么它会返回 0 (:0),如果它返回另一个值而不是 null,那么它将返回计数 (.length)。

更多正则表达式相关信息:https://www.rexegg.com/regex-quickstart.html

【讨论】:

  • 什么是“”元素?对不起,我对编码很陌生。
  • 如果第一个单词以a开头怎么办?然后a.match(/(\ba\S+\b)/ig).length; 不起作用
  • @Mukyuu 涵盖了所有场景。很好的答案!
  • 它显示一个错误,说它返回为空。
  • @JohnKosmalski 你的用例怎么样?
【解决方案2】:

使用indexOf的结果,0等价于startsWith

  var str = document.getElementById("myTextarea").value;
  var keyword = document.getElementById("myInput").value;
  var n = str.indexOf(keyword);`

this fiddle 中的工作示例。

HTH

【讨论】:

    【解决方案3】:

    function processText() {
        let pp = document.getElementById('root')
        console.log(pp.innerHTML.match(/(?<!\w)a\w*/g))
        return pp.innerHTML.match(/(?<!\w)a\w*/g);
    }
    processText()
    &lt;p id='root'&gt;this is a apple&lt;/p&gt;

    【讨论】:

      【解决方案4】:

      您可以获取 p 元素的内部文本 - 在空格处将其拆分以获取单词 - 将单词传递给函数以查看第一个字母是否为“a”,如果是,则增加计数。

      processText();
      
      
      function processText() {
        var p = document.querySelector('p').innerText; 
        var totalWords = p.split(' ');
        var wordsBegginingWithA = 0;
      
        totalWords.forEach(function(word){
          if ( beginsWithA(word) ) {
             wordsBegginingWithA++
           };
         })
              
        console.log(wordsBegginingWithA); // gives 5
      }
              
              
       function beginsWithA(word){
         return word.toLowerCase().charAt(0) == 'a';
       } 
      &lt;p&gt;Apples and oranges are fruit while red and blue are colors&lt;/p&gt;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多