javascript check if value has at least 2 or more words

13,909

Solution 1

str.trim().indexOf(' ') != -1 //there is at least one space, excluding leading and training spaces

Solution 2

The easy solution (not 100% reliable, since "foo   " returns 4, as @cookiemonster mentioned):

var str = "Big Brother";
if (str.split(" ").length > 1) {
    // at least 2 strings
}

The better solution:

var str = "Big Brother";
var regexp = /[a-zA-Z]+\s+[a-zA-Z]+/g;
if (regexp.test(str)) {
    // at least 2 words consisting of letters
}

Solution 3

You could use the String.Split() method:

function validateNameNumber(name) {
    var NAME = name.value;
    var values = name.split(' ').filter(function(v){return v!==''});
    if (values.length > 1) {
        //two or more words
        return true;
    } else {
        //not enough words
        return false;
    }
}

If you were to pass "John Doe" as the name value, values would equal {"john", "doe"}

http://www.w3schools.com/jsref/jsref_split.asp

Edit: Added filter to remove empty values. Source: remove an empty string from array of strings - JQuery

Share:
13,909
Bryce Hahn
Author by

Bryce Hahn

Coding I kind of my thing. Even though I'm just starting out on Java and am fairly new to it, I never give up on an idea and keep at it until I resolve the problem.

Updated on June 13, 2022

Comments

  • Bryce Hahn
    Bryce Hahn almost 2 years

    I have a field that you enter your name in and submit it. I would like the receive peoples first and last names and to do this i need to check if the value contains at least 2 words. This is what I am using right now but it doesn't seem to work.

    function validateNameNumber(name) {
        var NAME = name.value;
        var matches = NAME.match(/\b[^\d\s]+\b/g);
        if (matches && matches.length >= 2) {
            //two or more words
            return true;
        } else {
            //not enough words
            return false;
        }
    }