javascriptregexstringsyntaxobject-notation

Check String for Object/Dot Notation


I have a function that takes a string as an argument, my problem is that the string can be a sentence such as: "My name is John Doe. I need a car." or it can be a dot notation: "this.is.dot.notation". I don't know much about regex (if that's what I need) but I would like to separate the two types.

Is there a way to check if a string is in Object/Dot notation or not, assuming that the string can also be a word or a sentence? From https://stackoverflow.com/a/2390793/1251031, I thought of this, but this would not work with a sentence that may contain more than one period correct? Should regex be used?

if(input.split('.').length > 1){

}

Later, the dot notation will be used to access Object properties as seen here: Convert string in dot notation to get the object reference


Solution

  • Test if the string contains at least 2 dots, but no spaces. That seems to be the definition of dot notation.

    if (str.match(/\..*\./) && !str.match(/\s/)) {
        // dot notation
    } else {
        // sentence
    }
    

    Or maybe it's a dot that isn't at the end of the string, and no whitespace:

    if (str.match(/\.[^.]/) && !str.match(/\s)) {