1

username = "Npasandarshana@gmail.com"

password = "S@pasan123"

According to above example, string pattern "pasan" contains in the username.

I want to check whether all password or part of password contains in username for form validating before registration

i used javascript search function as below

password.search(username) == '-1' 

but It searches whole password string in the username and it is not accurate.

Can I use a regex pattern to check some scenario like above in javascript?

Niranga Sandaruwan
  • 691
  • 2
  • 19
  • 39
  • [**Here is a Java solution**](https://stackoverflow.com/questions/28761643/need-to-check-whether-password-contains-same-sequence-of-characters-of-username). You can adapt it to your needs. – Mistalis Jun 09 '17 at 10:03
  • [Levenshtein Distance](https://en.wikipedia.org/wiki/Levenshtein_distance) is sometimes used for this purposes – Hitmands Jun 09 '17 at 10:12
  • @Mistalis that solution doent give correct answer for me – Niranga Sandaruwan Jun 09 '17 at 10:51
  • According to Java solution when I split the username I get 3 substrings "Npasandarshana" "gmail" "com" but non of them contains password = "S@pasan123" in all of those substrings.but part of text in password "pasan" is contained in first substring.According to java logic that doesnt check. – Niranga Sandaruwan Jun 09 '17 at 10:54

2 Answers2

2

Match the string with a-z then .Array#filter the length above 4 and username contains

function check(use,pwd){
return pwd.match(/[a-z]+/ig).filter(a=> a.length > 4 && use.includes(a)).length > 0? true:false;
}
console.log(check("Npasandarshana@gmail.com","S@pasan123"))//true
console.log(check("Npasandarshana@gmail.com","S@pasysan123"))//false
prasanth
  • 22,145
  • 4
  • 29
  • 53
0

RegExp

var string = "foo",
    expr = /oo/;
if(expr.test(string)){
    console.log('Yes');
}else{
    console.log('No')
}

Match

var string = "foo",
    expr = "/oo/";
if(string.match(expr)){
    console.log('Yes');
}else{
    console.log('No')
}

(ES6) includes

var string = "foo",
    substring = "oo";
if(string.includes(substring)){
    console.log('Yes');
}else{
    console.log('No')
}

Also refer: How to check whether a string contains a substring in JavaScript?

Rushit
  • 526
  • 4
  • 13