在Javascript中计算标点符号然后传递给HTML

时间:2018-05-13 18:05:33

标签: javascript html

我正在尝试执行一个程序,用户将输入一个句子并计算该输入示例中的所有标点符号:

text =“He.llo,worl.d。!”

答案= 5

尽可能地,我希望从外部.js文件到html

的代码

这是我的代码:

function doCount(text, punct) {

  var text = document.getElementById('sentence1').text;
  var punct = [".", ",", "!", "?"];

  for (var i = 0; i < text.length; i++) {
    if (sentence1[i] == punct) {
        count++
      }
    }
    return count;
    document.getElementById("ans").innerHTML = count;
  }
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <script type="text/javascript" src="index.js"></script>
  <link rel="stylesheet" type="text/css" href="index.css">
</head>

<body>
  <h1>Punctuation Marks Counter! </h1>
  <input type="text" id="sentence1" class="box1">
  <button onclick="doCount();">Let's Count!</button>
  <p id="ans"></p>
</body>

</html>

3 个答案:

答案 0 :(得分:1)

试试这段代码:

function renderCount() {
  const text = document.getElementById('sentence1').value;
  const count = countPunctuationMarks(text);
  document.getElementById("ans").innerHTML = count;    
}

function countPunctuationMarks(str = "") {
  let count = 0;
  const marks = [".", ",", "!", "?"];

  for (const ch of str) {
    if (marks.includes(ch)) {
      count++;
    }
  }

  return count;
}

document.getElementById('countButton').addEventListener("click", renderCount);

HTML:

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <script type="text/javascript" src="./index.js"></script>
  <link rel="stylesheet" type="text/css" href="index.css">
</head>

<body>
  <h1>Punctuation Marks Counter! </h1>
  <input type="text" id="sentence1" class="box1">
  <button id="countButton">Let's Count!</button>
  <p id="ans"></p>
</body>

</html>

这是指向codesandbox的链接。

答案 1 :(得分:0)

var text = document.getElementById('sentence1').text;
var punct = [".", ",", "!", "?"];

var count = countPunc(text, punc);

document.getElementById("ans").innerHTML = count;


function countPunc(text, punc){
  var tempCount = 0;
  for (var i = 0; i < text.length; i++) {
    for (var j = 0; j < punct.length; j++) {
      if (text[i] == punct[i]) {
        tempCount++;
      }
    }
  }
  return tempCount;
}

答案 2 :(得分:0)

尝试一下:

    function countPunc(text, punc){
			return text.length - text.replace(punc,"").length;
    }
    
    //Test case
    var x = "This is a test with three dots ..."
    var m = countPunc(x, /[.,\/#!$%\^&\*;:{}=\-_`~()]/g) //count dots and more
    console.log(m)