Detect pattern of hyphens in the given string of three words

Viewed 123

I want to search if a string contains the following pattern which simply consists of two - signs (hyphens) separated with single words, not phrases or sentences:

word - word - word

Other conditions simply could be ignored. Spaces between don't affect the pattern so the above pattern and this one are the same:

word - word-word

If there is such a pattern I want to return true and else I want a false obviously!

So far I split the string by hyphens and check if there are two of them only and there are only 3 single words not more and not less, but I think there may be a more efficient way...

4 Answers

You can use the regular expression /^[a-z]+\s*-\s*[a-z]+\s*-\s*[a-z]+$/i.

Explanation:

/ - regular expression literal

^ - start of string

[a-z]+ - one or more lowercase alphabetic characters

\s* - zero or more whitespace characters

- - matches a literal hyphen character

$ - end of string

i - ignore case

function check(str){
  return /^[a-z]+\s*-\s*[a-z]+\s*-\s*[a-z]+$/i.test(str);
}
console.log(check('word - word - word'));
console.log(check('Word - word-word'));
console.log(check('invalid - string'));

You can use RegEx to resolve easily your question.

function myTest(str) {
    return /^\w+( ?- ?\w+){2}$/.test(str)
}

Edit : my answer is basically a TL;DR to this answer, which explains more deeply how it works. Note that you can change the \w+ with others expressions depending on how you define a word

Regular Expression can be used for this. The following regular expression will work for your use case.

^[a-z]+\s*-\s*[a-z]+\s*-\s*[a-z]+$

Example:

/^[a-z]+\s*-\s*[a-z]+\s*-\s*[a-z]+$/i.test("word - word - word");

You should be able to check for your pattern using a regular expression and the String.prototype.match() method:

'word-word-word'.match(/^(?:\w+\s?-\s?){2}\w+$/)  // --> will return an array containing the match

'word word word'.match(/^(?:\w+\s?-\s?){2}\w+$/)  // --> will return `null`

Now, that assumes that the examples above should not contain additional words around the pattern to be checked. If you want to allow for additional characters around the pattern you should be able to just omit the ^ and $ tokens in the pattern:

'something word-word-word somgthing'.match(/(?:\w+\s?-\s?){2}\w+/)  // --> will return an array containing the match

'something word word word something'.match(/(?:\w+\s?-\s?){2}\w+/)  // --> will still return `null`

Hope that helps!

Related