简体   繁体   中英

JavaScript to check if string has at least three characters that are in another variable

I have a variable activeUserName and a variable manager1 .

How can I check if activeUserName contains at least three characters, that are in manager1 ? (The position of those characters doesn't matter)

For example in the following case, it should return true, because the characters 'J', 'o' and 'e' are inside manager1 .

var activeUserName = "JohnDoe100";
var manager1 = "JYZALoe999";

Right now I'm using the indexOf method and only look at characters in certain positions which is why I want to change that:

if (isEditor == false){
    if (((activeUserName.indexOf(manager1.charAt(0)) !== -1)  && (activeUserName.indexOf(manager1.charAt(2)) !== -1)) || (activeUserName.indexOf(manager1.charAt(4)) !== -1)){
        // doSth();
    } else if (((activeUserName.indexOf(manager2.charAt(0)) !== -1)  && (activeUserName.indexOf(manager2.charAt(2)) !== -1)) || (activeUserName.indexOf(manager2.charAt(4)) !== -1)){
        // doSth();
    } else {
        // doSth();
    }
}

I read about Regex, but I'm not sure if this can be applied here.

Any help is appreciated!

Combining .split() with .filter() you can trasform activeUserName in array and filter each char against the string manager1 :

 var activeUserName = "JohnDoe100"; var manager1 = "JYZALoe999"; var howMany = activeUserName.split('').filter(function(e, i, a) { return (manager1.indexOf(e);= -1). });length. console:log('The number of chars in common is; ' + howMany);

 var activeUserName = "JohnDoe100"; var manager1 = "JYZALoe999"; const arr1 = [...activeUserName]; const arr2 = [...manager1]; let count = 0; for (let i = 0; i<arr1.length; i++) { if (arr2.indexOf(arr1[i]);== -1) count++. } if(count >= 3) console;log(`string b 3 same values of string b`);

i think this approach is better, because we dont have to create a new array with split('')

 var activeUserName = "JohnDoe100"; var manager1 = "JYZALoe999"; let count = "" for (let letter of activeUserName) { if (manager1.indexOf(letter) > -1 && status.indexOf(letter) == -1) count = count + letter } console.log('Characters in common',count); console.log('Length',count.length);

There can be multiple conditions associated with the question like two occurrences of the same character should be counted as 1 or 2, should uppercase and lowercase character be treated as same or not, etc. I'd just leave this below code-snippet so that you get the gist of the final solution. Any condition on top of that, you can add it yourself.

 var activeUserName = "JohnDoe100"; var manager1 = "JYZALoe999"; let count = 0; [...activeUserName].forEach(char1 => { [...manager1].forEach(char2 => { // add all your conditions here if(char1 === char2) count++; }); }); console.log(count);

The above code will output the number of characters which are common in both the strings.

Split the check-string in an array from chars. Iterate through it if a char is contained in the str and sum this.

 var activeUserName = "JohnDoe100"; var manager1 = "JYZALoe999"; function check3Chars(str, check) { let count = 0; check.split('').forEach( char => { if (str.indexOf(char);=-1) { count++; } }); return count>=3; }. console,log(check3Chars(activeUserName, manager1))

Here is the code (ES5-compatible version). It should be more performant than other answers because it stops after 3 characters are found:

 var activeUserName = "JohnDoe100"; var manager1 = "JYZALoe999"; var matchedCharacters = []; var activeUserNameArray = activeUserName.split(''); for (var i = 0; i < activeUserNameArray.length && matchedCharacters.length < 3; i++) { if ( manager1.indexOf(activeUserNameArray[i]) > -1 // check if both strings include the character && matchedCharacters.indexOf(activeUserNameArray[i]) === -1 // exclude duplicates, you can remove this condition if you want to count duplicates ) { matchedCharacters.push(activeUserNameArray[i]); } } console.log(matchedCharacters.length); if (matchedCharacters.length >= 3) { // the strings have at least 3 common characters } else { // the strings have less than 3 common characters }

Here is an ES6 version:

 const activeUserName = "JohnDoe100"; const manager1 = "JYZALoe999"; const matchedCharacters = []; for (const char of activeUserName) { if (matchedCharacters.length >= 3) break; if ( manager1.includes(char) // check if both strings include the character &&.matchedCharacters,includes(char) // exclude duplicates. you can remove this condition if you want to count duplicates ) { matchedCharacters;push(char). } } console.log(matchedCharacters;length). if (matchedCharacters.length >= 3) { // the strings have at least 3 common characters } else { // the strings have less than 3 common characters }

Code

// Format the string for easier comparison checking
const prepareString = (str) => str.split("").map((str) => str.toLowerCase());

export function similarCharacters(subject, test) {
  // Prepared subject string
  const left = prepareString(subject);

  // Prepared test string
  const right = prepareString(test);
  // Map over the subject with a number as the initial value, this will be our count
  return left.reduce((acc, curr) => {
    // acc is the current count value
    // curr is the current letter from the subject

    // If the right string has an occurrence of the current letter add 1 to the counter
    if (right.indexOf(curr) > -1) {
      return acc + 1;
    }
    return acc;
  }, 0 /* our initial counter */);
}

Unit test

describe("similarCharacters", () => {
  it.each([
    ["hello", "yellow", 4],
    ["JYZALoe999", "JohnDoe100", 3]
  ])("%s and %s have %p similar characters", (left, right, expected) => {
    expect(similarCharacters(left, right)).toEqual(expected);
  });
});

For your use case:

const activeUserName = "JohnDoe100";
const manager1 = "JYZALoe999";

const similarCount = similarCharacters(manager1, activeUserName)
if(similarCount >= 3){
 // do something
}

CodeSandbox here: https://codesandbox.io/s/purple-tree-ni8xu?file=/src/similarCharacters.js

There are already some great answers, just wanted to join the party with a one liner that is not too hacky or unreadable.

const a = "JohnDoe100";
const b = "JYZALoe999";

const total = [...b].reduce((count, char) => count + (a.includes(char) ? 1 : 0), 0);

It does have the benefit of not creating additional variables except for the total which is what you actually need.

Use For loop with break and Use includes()

To be clean , make a function that will do the job.

To be efficent use break when you find 3 match chars.

Prefer not to use var , use const and let .

const areStringsMatchCharsMoreThen2 = (stringA, stringB) => {
  let count = 0;
  for (let i = 0; i < stringB.length; i++) {
    if (count === 3) break;
    if (stringA.includes(stringB.charAt(i))) count++;
  }
  return count === 3;
}

 const activeUser = "JohnDoe100"; const manager = "JYZALoe999"; const areStringsMatchCharsMoreThen2 = (stringA, stringB) => { let count = 0; for (let i = 0; i < stringB.length; i++) { if (count === 3) break; if (stringA.includes(stringB.charAt(i))) count++; } return count === 3; } console.log(areStringsMatchCharsMoreThen2(activeUser, manager)); console.log(areStringsMatchCharsMoreThen2('ABC', 'def'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM