如何在JQuery中获得一个字符串的长度
这个任务是在JQuery的帮助下获得一个字符串的长度。我们可以通过jQuery的.length属性找到字符串的长度。length属性包含了jQuery对象中的元素数量。因此,它可以用来获取或找出一个字符串中的字符数。
语法:
$(selector).length
示例 1:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Find Length of a String Using jQuery</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js">
</script>
<script type="text/javascript">
(document).ready(function() {
("button").click(function() {
var myStr = ("textarea").val();
if ((this).hasClass("with-space")) {
var withSpace = myStr.length;
alert(withSpace);
} else if ($(this).hasClass("without-space")) {
var withoutSpace = myStr.replace(/ /g, '').length;
alert(withoutSpace);
}
});
});
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<h3>Enter Text and Click the Buttons</h3>
<textarea rows="5" cols="60">
How do you get the length of a string in JQuery?
</textarea>
<br>
<button type="button" class="with-space">
Length of string including white-spaces
</button>
<br>
<br>
<button type="button" class="without-space">
Length of string without white-spaces
</button>
</body>
</html>
输出:
在点击按钮之前。
示例 2:
<!DOCTYPE html>
<html>
<head>
<title>
Find Length of a String Using jQuery
</title>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script>
(function() {
('#geeks1').keyup(function() {
var txtlen = (this).val().length;
var txtlennospace =(this).val().replace(/\s+/g, '').length;
('#geeks1_space').text(txtlen);
('#geeks1_space_no_space').text(txtlennospace);
});
});
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<div style="padding-bottom: 10px;">JQuery - Realtime length</div>
<div>
<input style="padding: 7px;"
maxlength="60"
size="50"
type="text"
id="geeks1" />
<p>Length with space :
<span id="geeks1_space"></span></p>
<p>Length without space :
<span id="geeks1_space_no_space"></span></p>
</div>
</body>
</html>
输出:
在进入文本之前。
输入文本后。