如何用JQuery计算一个字符串中的字数
为了计算一个字符串中的字数,我们可以使用JQuery split()方法,同时使用或不使用trim()方法。
.split()方法简单地将一个字符串按指定的字符分割成一个子字符串数组,.trim()方法去除前面和后面的空白。
语法:
string.split(separator, limit)
步骤:
* 从HTML元素中获取字符串。
* 在空白处的基础上将字符串分割成子串。
* 计算子字符串的数量。
例子1:伴随着trim()方法,从字符串中去除开始和结束的空格。
<!DOCTYPE html>
<html>
<head>
<title>How to calculate the number
of words in a string using Javascript?</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js">
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<h3>How to calculate the number of words
in a string using Javascript?</h3>
<textarea> Geeks For GEEKS </textarea>
<br>
<button type="button">Click</button>
<script type="text/javascript">
(document).ready(function() {
("button").click(function() {
// reduce the whitespace from both sides of a string.
var geeks1 = .trim(("textarea").val());
//split a string into an array of substrings
var geek = geeks1.split(" ")
// count number of elements
alert(geek.length);
});
});
</script>
</body>
</html>
输出:
- 在点击按钮之前。

- 点击按钮后。

例子2:没有trim()方法
<!DOCTYPE html>
<html>
<head>
<title>Calculate the number
of Words in a String</title>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<h3>How to calculate the number of
words in a string using Javascript?</h3>
<p id="geeks1"></p>
<br>
<button onclick="myFunction()">Click</button>
<p id="geeks"></p>
<script>
var str = "Geeks For Geeks";
document.getElementById("geeks1").innerHTML = str;
function myFunction() {
var res = str.split(" ");
document.getElementById(
"geeks").innerHTML = res.length;
}
</script>
</body>
</html>
输出:
- 在点击按钮之前。

- 点击按钮后。

极客教程