html 我试过这个,但是,如何得到的数字,每个字母在指定的字符串在网页

ulydmbyx  于 2023-01-15  发布在  其他
关注(0)|答案(1)|浏览(107)

如何获得在输入文本字段中输入的指定字符串中每个字母的出现次数?
我试过这个:

<!DOCTYPE html>
<html>
    <head>
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Web Page</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">

<style>
    body {
  background: #007bff;
  background: linear-gradient(to right, #0062E6, #33AEFF);
  font-family: 'Poppins', sans-serif;
}
</style>
<script type="text/javascript">
    window.onload = btn;

function btn() {
  document.getElementById("btn").onclick = showText;
}

function showText() {
  var text = "";
  var inputOne = document.getElementById("txtBox").value;
  var inputTwo = document.getElementById("numBox").value;
  var i=1; // to control the loop
  while (i <= inputTwo) {    // i goes from 1 to inputTwo
    text += inputOne;
    i++;
  }
  document.getElementById("showCode").innerHTML = text;
}

function Char_Counts(str1) {
var uchars = {};
str1.replace(/\S/g, function(l){uchars[l] = (isNaN(uchars[l]) ? 1 : uchars[l] + 1);});
return uchars;
}
console.log(Char_Counts("The quick brown fox jumps over the lazy dog"));

  </script>
    </head>

<body style="text-align:center;">
    <h1 style="color:green;">
        Sample Web Page
    </h1>
    <p>
        Enter Your text below:
    </p>
<div class="container">
    <input type="text" id="txtBox"><br/> <input type="number" id="numBox"><br/><br/>
<button type="button" id="btn" class="btn btn-warning">Click Me!</button> <br/>

<p id="showCode"></p>
</div>
</body>

</html>
vpfxa7rd

vpfxa7rd1#

这将输出一个简单的json字符串,该字符串对应于您在txtBox输入字段中键入的字符串的字母计数。

function showText() {
  var inputOne = document.getElementById("txtBox").value;
  document.getElementById("showCode").textContent = Char_Counts(inputOne);
}

function Char_Counts(str1) {
    var uchars = {};
    str1.replace(/\S/g, function(l){uchars[l] = (isNaN(uchars[l]) ? 1 : uchars[l] + 1);});
    return JSON.stringify(uchars);
}

您可以从代码中删除<input type="number" id="numBox">console.log(Char_Counts("The quick brown fox jumps over the lazy dog"));

相关问题