How to check if one String completes another?

Asked

Viewed 123 times

4

would like to know if there is any function or operator that can check if a String looks like another in javascript for example:

var str1 = "joao foi ao mercado";
var str2 = "joao fo";

What I need is to compare the first with the second, if the second is a piece of the first then returns true (type the mysql like)

  • Take a look https://en.wikipedia.org/wiki/Levenshtein_distance

  • Or this question in the English OS describing the % similarity https://stackoverflow.com/questions/10473745/compare-strings-javascript-return-likely

4 answers

3


3

One option is to use the method String.prototype.search(). If the return is -1 does not exist, otherwise it is because it exists. See:

var str1 = "O menino joao foi ao mercado";
var str2 = "joao fo";

function compare(str1, str2){
    return (str1.search(str2)>0)? true : false;
}

console.log(compare(str1,str2)); //true

If you prefer also, another option would be to use regular expression. For this case it will return false or true can the string 2 be anywhere in the string 1. Behold:

var str1 = "O menino joao foi ao mercado";
var str2 = "joao fo";

var rx = new RegExp(str2);

console.log(rx.test(str1)); //true

There is also the String.prototype.includes():

var str1 = "O menino joao foi ao mercado";
var str2 = "joao fo";


console.log(str1.includes(str2));  // true
console.log(str1.includes("joac"));  // false

1

It would be an option to use index and do its own function?

function ContemString(str1, str2){
    return str1.indexOf(str2) > -1;
}

1

The method search() Locates the first character substring match in a regular expression search.

var str = "joao foi ao mercado",
substring = /joao fo/;

var pos = str.search(substring);
console.log(pos);

var str = "joao foi ao mercado",
substring = /joao não fo/;

var pos = str.search(substring);
console.log(pos);

var str = "joao foi ao mercado",
substring = /fo/;

var pos = str.search(substring);
console.log(pos);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.