Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

So sánh hai câu từ từng từ và kiểm tra substring trong JavaScript

Nhận hai chuỗi, trả về true nếu a là substring của b hoặc ngược lại, ngược lại false.

Ví dụ: isSubstr('hello', 'hello world') // true, isSubstr('can I use', 'I us') // true, isSubstr('can', 'no we are') // false.

Hàm kiểm tra chuỗi dài hơn có chứa chuỗi ngắn hơn không.

Ví dụ

const str1 = 'This is a self-driving car.';
const str2 = '-driving c';
const str3 = '-dreving';

const isSubstr = (first, second) => {
  if (first.length > second.length) {
    return first.includes(second);
  }
  return second.includes(first);
};

console.log(isSubstr(str1, str2));
console.log(isSubstr(str1, str3));

Kết quả

Đầu ra trong console sẽ là:

true false