Reputation: 21
I want to validate my initials with regex in JavaScript, the rule should match any letter combination and should not be case sensitive.
Example (Liza Suki):
var a = "ls"; // valid
var b = "sl"; // valid
var c = "Ls"; // valid
var d = "LS"; // valid
var e = "lS"; // valid
var f = "Sl"; // valid
var g = "SL"; // valid
var h = "sL"; // valid
Thanks in advance.
Upvotes: 1
Views: 172
Reputation: 785276
Here is a generic function that takes a name and input initials value and it validates whether name has same initials or not.
function isValid(name, ils) {
var m = name.match(/\b[A-Z]/g);
var re = new RegExp('^' + m.map(function(e){return '(?=.*?' + e + ')';}).join('') +
'[' + m.join('') + ']{' + m.length + '}$', 'i');
// Example: re = /^(?=.*?s)(?=.*?l)[sl]{2}$/i
return re.test(ils);
}
Testing:
isValid('Liza Suki', 'sl')
true
isValid('Liza Suki', 'ss')
false
isValid('Liza Suki', 'ls')
true
isValid('Liza Suki', 'LS')
true
isValid('Liza Suki', 'LL')
false
isValid('Liza Suki', 'lsl')
false
Upvotes: 1
Reputation: 950
Try this one (the 'i' flag means, that regex is case-insensitive):
/(ls)|(sl)/i
https://regex101.com/r/mT8jW3/2
Upvotes: 4
Reputation: 174716
Anchors must be a needed one.
/^[ls]{2}$/i
Try this if you don't want to match ll
or ss
/^(?!(?:ss|ll)$)[ls]{2}$/i
Upvotes: 3
Reputation: 18762
var regex = /(ls)|(sl)/i;
console.log(regex.test('LS'));
console.log(regex.test('lS'));
console.log(regex.test('Ls'));
console.log(regex.test('sL'));
console.log(regex.test('ll'));
console.log(regex.test('SS'));
Output
true
true
true
true
false
false
Upvotes: 1