How to check if a text is all white space characters in client side?

后端 未结 11 1151
心在旅途
心在旅途 2020-12-23 11:14

How to check if a user input text is all white space characters (space, tab, enter etc) in client side?

11条回答
  •  轮回少年
    2020-12-23 11:59

    /^\s+$/.test(userText)

    Change the + to * to include the empty string '' as a positive match.

    Edit

    More often than not though you need to trim whitespace from user-entered text and simply test if it's non-empty:

    userText = userText.replace(/^\s+/, '').replace(/\s+$/, '');
    if (userText === '') {
        // text was all whitespace
    } else {
        // text has real content, now free of leading/trailing whitespace
    }
    

提交回复
热议问题