Detect if string contains any spaces

后端 未结 5 707
醉酒成梦
醉酒成梦 2020-12-23 11:24

How do I detect if a string has any whitespace characters?

The below only detects actual space characters. I need to check for any kind of whitespace.



        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-23 11:59

    A secondary option would be to check otherwise, with not space (\S), using an expression similar to:

    ^\S+$
    

    Test

    function has_any_spaces(regex, str) {
    	if (regex.test(str) || str === '') {
    		return false;
    	}
    	return true;
    }
    
    const expression = /^\S+$/g;
    const string = 'foo  baz bar';
    
    console.log(has_any_spaces(expression, string));

    Here, we can for instance push strings without spaces into an array:

    const regex = /^\S+$/gm;
    const str = `
    foo
    foo baz
    bar
    foo baz bar
    abc
    abc abc
    abc abc abc
    `;
    let m, arr = [];
    
    while ((m = regex.exec(str)) !== null) {
    	// This is necessary to avoid infinite loops with zero-width matches
    	if (m.index === regex.lastIndex) {
    		regex.lastIndex++;
    	}
    
    	// Here, we push those strings without spaces in an array
    	m.forEach((match, groupIndex) => {
    		arr.push(match);
    	});
    }
    console.log(arr);


    If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


    RegEx Circuit

    jex.im visualizes regular expressions:

提交回复
热议问题