Reputation: 180
I need to achieve a particular task in javascript, in which my goal is to match the string which starts with a char from a specific set of characters like vowel and ends with the same character where the length of the string is greater than three.
so far I have done the following code that starts and ends with the same character but doesn't know how to specify it that the first char is from the specific set of character:
function regexVar() {
var re = /(.).*\1/
return re;
}
console.log("obcdo".test(s));
let suppose the specific set of chars is the vowel
(a, e, i, o, u)
in this case:
abcd ----> false
obcdo ----> true
ixyz ----> false
Upvotes: 2
Views: 2058
Reputation: 11
function regCheck(string){
let re = new RegExp(/^(a|e|i|o|u).*\1$/g);
return re.test(string);
}
regCheck('aewxyzae')
Upvotes: 0
Reputation: 574
If we are taking the set of vowels then,the regular expression for words beginning and ending with the same vowel is:
var re = /(\ba(\w+)a\b|\be(\w+)e\b|\bi(\w+)i\b|\bo(\w+)o\b|\bu(\w+)u\b)/g;
Upvotes: 0
Reputation: 370729
You need to use a character set to ensure the captured character is one of the ones you want, backreference the first captured group at the end of the pattern, not the third group (your pattern doesn't have 3 capture groups), use ^
and $
to anchor the pattern to the start and end of the string, and repeat with {2,}
rather than *
to make sure the whole string is at least 4 characters long:
/^([aeiou]).+\1$/
const re = /^([aeiou]).{2,}\1$/
console.log(
re.test('abcd'),
re.test('obcdo'),
re.test('ixyz')
);
Upvotes: 3
Reputation: 37755
You can use this pattern
/^([aeiou]).+\1$/i
^
- Start of string([aeiou])
- Matches a,e,i,o,u
any one of that. (group 1).+
- Match anything except new line. \1
- Match group 1$
- End of stringlet startAndEnd = (str) =>{
return /^([aeiou]).+\1$/i.test(str)
}
console.log(startAndEnd(`ixyz`))
console.log(startAndEnd(`abcd`))
console.log(startAndEnd(`obcdo`))
Upvotes: 0