JS to determine if the string is all empty (using trim function/Regular expression)

Source: Internet
Author: User

We need to determine whether the user input is all spaces, you can use the following methods: Method one: Using Trim ()
/* 使用String.trim()函数,来判断字符串是否全为空*/function kongge1(test) {    let str = test.trim();    if (str.length == 0) {        console.log(‘字符串全是空格‘);    } else {        console.log(‘输入的字符串为:‘ + test);    }}
If trim () does not exist, you can execute the following code before all code/ * Add method trim to string prototype chain Object */
if (! String.prototype.trim) {
String.prototype.trim = function () {
Return This.replace (/^[\s\ufeff\xa0]+|[ \s\ufeff\xa0]+$/g, ");
};
}For example:/* Use the String.Trim () function to determine whether the string is all empty */function kongge1 (test) {/* Adds a method trim */if (!) to the string prototype chain object. String.prototype.trim) {String.prototype.trim = function () {return this.replace (/^[\s\ufeff\xa0]+|[ \s\ufeff\xa0]+$/g, "); }; } Let str = Test.trim (); if (Str.length = = 0) {console.log (' string is all spaces '); } else {console.log (' Input string: ' + Test '); }}

Method Two: Use regular expressions
/* 使用正则表达式来判断字符串是否全为空 */function kongge2(test) {    if(test.match(/^\s+$/)){      console.log("all space or \\n");                }    if(test.match(/^[ ]+$/)){      console.log("all space")    }    if(test.match(/^[ ]*$/)){      console.log("all space or empty")    }    if(test.match(/^\s*$/)){      console.log("all space or \\n or empty")    } else {        console.log(‘输入的字符串为:‘ + test);    }}
Case:
<! DOCTYPE html>

JS to determine if the string is all empty (using trim function/Regular expression)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.