How do you detect the difference between two similar words?
For example:
wordcompared toword,gives,as a variablethiscompared to.thisgives.as a variableinfocompared to:info,gives:and,as a variable
In this case we always know which word is the longer one. And the actual word is always the same for the comparison. It's just that the longer one maybe has some extra characters.
I need to do this using javascript only.
2 Answers 2
You could try checking for difference between the array of characters.
var shortStr = 'info';
var longStr = ':info,';
console.log(Array.from(longStr).filter(function(c) {
return Array.from(shortStr).indexOf(c) === -1;
}));
1 Comment
Also, there's a better way, check if the string is a sub-string, and then remove the sub-string from the main string:
function checkDiff(a, b) {
var big = '', small = '';
if (a.length > b.length) {
big = a;
small = b;
} else {
small = a;
big = b;
}
if (big.indexOf(small) != -1) {
return big.replace(small, "");
} else {
return false;
}
}
alert(checkDiff("word", "word,"));
alert(checkDiff("this", ".this"));
alert(checkDiff("info", ":info,"));
I have added demo for all your cases. It returns the values as a single string, based on the place it has occurred. You can send the output as an array as well, using the .split() method.
function checkDiff(a, b) {
var big = '', small = '';
if (a.length > b.length) {
big = a;
small = b;
} else {
small = a;
big = b;
}
if (big.indexOf(small) != -1) {
console.log(big.replace(small, "").split(""));
return big.replace(small, "").split("");
} else {
return false;
}
}
alert(checkDiff("word", "word,"));
alert(checkDiff("this", ".this"));
alert(checkDiff("info", ":info,"));
3 Comments
console.log as well to check in console if it works fine. And it does return the different values as an array, on the basis of the occurrence.
:)It's possible. The link I sent you is JavaScript. What do you think it is then?