试图找到以a开头的单词

时间:2019-03-01 03:24:31

标签: javascript html

我正在编写一些代码来查找以字母“ 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>

4 个答案:

答案 0 :(得分:1)

您可以使用: [variablename].match( /(?<!\w)a\w*/ig )!=null? a.match(/(?<!\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();
<span id="p">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.</span>

说明:.match将返回与给定表达式匹配的所有值。 注意,我还使用了conditional (ternary) operator来检测如果未返回匹配项,则Regex是否返回空值。如果返回null,则返回0(:0),如果返回的值不是null,则返回计数(.length)。

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

答案 1 :(得分:1)

您可以获取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';
 } 
<p>Apples and oranges are fruit while red and blue are colors</p>

答案 2 :(得分:0)

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()
<p id='root'>this is a apple</p>

答案 3 :(得分:0)

使用indexOf的结果,0等于startsWith

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

this fiddle中的工作示例。

HTH