我想知道如何使用e
循环和增加的子字符串在文本中找到多少个字符,例如for
,以便遍历整个文本。
这是我到目前为止所得到的。
<p id="paragraph"> this is the sentence, how many letters "e" can you find? How many "is" can you find</p>
<input type="text" id="text"/> <input type="button" value="search" onclick="search()"/>
<p id="howmany"></p>
function search() {
var letter = document.getElementById("text").value;
var text = document.getElementById("paragraph").innerHTML;
var count = 0;
var string = text.substring(0);
for(var i = 0; i < text.length, i++) {
count++
}
document.getElementById("howmany").innerHTML = ("The result is" + count)
}
我只收到文字中有多少个字符,但我想查找文本中有多少e
或is
或其他内容。我知道有些东西不见了但是什么?
答案 0 :(得分:0)
没有必要为此循环 - 您可以使用正则表达式并计算匹配项:
string.match(/e/g).length
string.match(/is/g).length
也就是说,代码中还有很多其他错误:
function search() {
var letter = document.getElementById("text").value;
var text = document.getElementById("paragraph").innerHTML;
var count = 0;
var string = text.substring(0,text.lenght); // should be length; or else not needed at all
for(var i = 0; i < text.length, i++) {
count++
}
document.getElementsById("howmany").innerHtml = ("The result is" + count) // it's getElementById, not getElements; it's innerHTML, not innerHtml
}
另外:onclick
,clickOn
。
答案 1 :(得分:0)
我自己对这个问题的看法:
function howMany () {
var needle = document.getElementById('text').value.trim(),
textProp = 'textContent' in document ? 'textContent' : 'innerText',
haystack = document.getElementById('paragraph')[textProp].trim(),
result = haystack.match(new RegExp(needle, 'g'));
document.getElementById('howmany')[textProp] = result ? result.length : 0;
}
document.querySelector('input[type=button]').addEventListener('click', howMany);
&#13;
#howmany::before {
content: 'Matches found: ';
}
#howmany:empty::before {
content: '';
}
&#13;
<p id="paragraph">This is the sentence, how many letters "e" can you find? How many "is" can you find</p>
<label>String to find: <input id="text" placeholder="what are you looking for?" /></label>
<input type="button" value="search" />
<p id="howmany"></p>
&#13;
参考文献: