trim() से String Cleaning
In this page:
var clean = $.trim(string);
trim() क्या है?
$.trim() किसी string की सिर्फ बिल्कुल शुरुआत और अंत से whitespace characters हटाता है, text के बीच में मौजूद spacing को पूरी तरह untouched छोड़ते हुए।
उदाहरण: What is trim()?
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
console.log("[" + $.trim(" hello ") + "]");
</script>
</body>
</html>
User Input Trim करना
Users अक्सर गलती से अपने input के आसपास extra spaces type कर देते हैं — अपने name से पहले, अपने email address के बाद — खासकर mobile keyboards पर।
उदाहरण: Trim User Input
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="name" value=" Alice ">
<script>
console.log($.trim($("#name").val()));
</script>
</body>
</html>
Validation से पहले Trim करें
किसी field के खाली होने की जाँच करने से पहले हमेशा input trim करें, क्योंकि सिर्फ spaces वाली एक string अन्यथा एक empty check pass कर जाएगी भले ही वह।
उदाहरण: Trim Before Validation
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="name" value=" ">
<script>
if ($.trim($("#name").val()) === "") {
console.log("Name is empty");
}
</script>
</body>
</html>
बीच के Spaces रहते हैं
trim() सिर्फ string की बिल्कुल शुरुआत और अंत में whitespace को touch करता है — बीच में words के बीच के कोई भी spaces या line breaks बिल्कुल वैसे ही रहते हैं।
उदाहरण: Middle Spaces Stay
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
console.log($.trim(" hello world "));
</script>
</body>
</html>
एक छोटा trim() Project
एक simple, common pattern यह है कि किसी form को validate या submit करने से ठीक पहले हर text input को trim कर दिया जाए, ताकि accidental leading या trailing spaces कभी।
उदाहरण: Small trim() Project
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input id="email" value=" [email protected] ">
<script>
$("#email").on("blur", function() {
$(this).val($.trim($(this).val()));
});
</script>
</body>
</html>
- यह उम्मीद करना कि
$.trim(" a b ")words के बीच के spaces हटा देगा, जबकि यह सिर्फ शुरुआत और अंत हटाता है। $.trim(null)call करना या किसी number पर call करना और यह मान लेना कि यह same value return करेगा, जबकि यहnullयाundefinedके लिए एक empty string return करता है।- नए code में
$.trim()इस्तेमाल करना, जबकि यह jQuery 3.5 से deprecated है और nativeString.prototype.trim()वही काम करता है:" hi ".trim()।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: