0

Для частичного совпадения в строке я использую метод .includes,

var str = 'man';
'woman'.includes(str);//true

Но если в str будет пустая строка, то метод тоже вернёт true. Нужно либо сделать так, чтобы метод includes возвращал false при пустой строке, либо искать другое решение, которое я к сожалению не нашел.

1
  • 1
    Используйте тернарный оператор, проверяющий, пуста ли строка-шаблон.
    – Akina
    28 янв 2021 в 5:55

1 ответ 1

4

Добавление к комментарию @Akina

function _includes(str, fstr) {
  return (!!fstr && fstr.length) 
    ? str.includes(fstr)
    : false;
}


console.log(_includes('', 'man'));
console.log(_includes('go', 'man'));
console.log('------>', _includes('goman', 'man'));
console.log(_includes('12goma1ngo', 'man'));
console.log('------>', _includes('mango', 'man'));
console.log(_includes('null', false));
console.log(_includes('false', false));
console.log(_includes('null', null));
console.log(_includes('false', null));
console.log(_includes(null, ''));
console.log(_includes(true, null));
console.log(_includes(undefined, undefined));
console.log(_includes(undefined, []));
console.log(_includes({}, []));
console.log(_includes(NaN, []));
console.log(_includes([], NaN));

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.