Lately I've been facing an issue on JavaScript (node). Basically I have a string (which can be anything since it is inputted by a user) and I have to check:
- If the string letters are all in lowercase;
- If the string doesn't have any special characters (é-[ã*$, etc (that was just an example);
- If the string has no numbers;
- If the string, if it has more than one word, has only one blank/white space between all words. Nothing more, nothing less.
I know that might be too much, but I have no other option than ask for help since I'm not an expert on using RegEx.
PS: The closer I got was using this:
const regexPattern = string.match(/^[^a-z] $/) ? false : true;
But this only works for one word and that's it. If there's more than one word it will do nothing to the other words, and what I need is to check if every word and check if there is only one white space between them.
Thanks! I really appreciate it!
CodePudding user response:
This is a non regex solution
You can split the string by a space and use Array.every
to check whether every word in the string matches the regex.
Also, your regex should be /^[a-z] $/
. Remove the ^
, since it inverts the condition.
function validate(str){
return str.split(" ").every(e => /^[a-z] $/.test(e))
}
console.log(validate("hello world"))
console.log(validate("hello"))
console.log(validate("hello world"))
CodePudding user response:
Here is a working regex: /^([a-z] |([a-z] [a-z] ) )$/
const regexPattern = /^([a-z] |([a-z] [a-z] ) )$/
console.log(regexPattern.test('this should work')) // true
console.log(regexPattern.test('thisshouldwork')) // true
console.log(regexPattern.test('this should not work')) // false
console.log(regexPattern.test('thisshouldnotwork ')) // false
console.log(regexPattern.test('$% this should not work')) // false
console.log(regexPattern.test(' ')) // false