0

Want to know if the substring of string is in the another string.

For eg..

var firstString= test123; var secondString= nest145; var thirdString= test456; var fourString= teating456;

Result should be after comparing firstString and secondString

est1 is matched.

Result should be after comparing firstString and thirdString

test is matched.

Result should be after comparing firstString and fourString

No match found.

Limit to check the word-length can be decided.For the above example it is 4

0

3 Answers 3

3

Here is a simple sample, where the matched letters needs to be next after each other.

var firstString = 'test123';
var secondString = 'nest145';
var thirdString = 'test456';
var fourString = 'teating456';

function findMatchedChars(str1, str2, limit) {
  var result = '', s1 = str1, s2 = str2;
  if (str2.length > str1.length) {
    s1 = str2;
    s2 = str1;
  }
  for (var x = 0; x < s1.length; x++) {
    if (s1[x] == s2[x]) {
      result += s1[x];
    } else {
      if (result.length > 0 && result.length >= limit) return result;
      result = '';
    }
  }
  if (result.length > 0 && result.length >= limit) return result;
  return 'No matches';  
}

alert(findMatchedChars(firstString,secondString,4));
alert(findMatchedChars(firstString,thirdString,4));
alert(findMatchedChars(firstString,fourString,4));

Sign up to request clarification or add additional context in comments.

1 Comment

@Vaibs_Cool You're welcome, I also made an update to make it more solid.
0

This is LCS problem with tow string... LCS

Comments

0

Here is the regex version:

var firstString = 'test123';
var secondString = 'nest145';
var thirdString = 'test456';
var fourString = 'teating456';

function findDups(str1, str2, limit) {
  var re = '.*([^\\s]{' + limit + '}).*\\s+.*\\1.*'
  var m = (str1 + " " + str2).match(re)
  if (m != null) {
    alert(m[1])
  } else
    alert('No matches')
}

findDups(firstString, secondString, 4)
findDups(firstString, thirdString, 4)
findDups(firstString, fourString, 4)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.