Liza Suki
Liza Suki

Reputation: 21

Validating initials with regex in JavaScript

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

Answers (5)

anubhava
anubhava

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

artm
artm

Reputation: 8584

i is case insensitive, g is global:

/(ls)|(sl)/ig

Upvotes: 2

Kamil Szymański
Kamil Szymański

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

Avinash Raj
Avinash Raj

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

DEMO

Upvotes: 3

Wand Maker
Wand Maker

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

Related Questions