Javascript string ends with you

Проверьте, заканчивается ли строка другой строкой в JavaScript

В этом посте мы обсудим, как проверить, заканчивается ли строка другой строкой в JavaScript.

1. Использование endsWith() метод

Рекомендуемое решение — использовать нативный метод JavaScript. endsWith() чтобы определить, начинается ли строка с указанной строки. Это показано ниже:

Этот метод был добавлен в спецификацию ES6 и пока может быть доступен не во всех реализациях JavaScript. Однако вы можете использовать следующий полифилл из MDN:

2. Использование библиотеки Lodash/Underscore

В качестве альтернативы вы можете использовать Lodash или же Underscore.string библиотека, которая предлагает _.endsWith метод. Он проверяет, заканчивается ли строка заданной целевой строкой.

3. Использование lastIndexOf() метод

Здесь идея состоит в том, чтобы найти индекс последнего вхождения данной строки. В следующем примере кода показано, как реализовать это с помощью lastIndexOf() метод.

Поскольку lastIndexOf() метод возвращает -1, код завершится ошибкой, если длина строки на единицу меньше длины целевой подстроки. Вот как с этим справиться:

4. Использование indexOf() метод

В качестве альтернативы, с помощью indexOf() метод, вы можете сделать так:

Читайте также:  placeholder

5. Использование substring() метод

The substring() метод используется для получения строки между указанными индексами. Это можно использовать следующим образом:

6. Использование slice() метод

Альтернативно, slice() метод может быть вызван вместо substring() метод:

Вы также можете использовать отрицательные индексы с slice() метод:

7. Использование регулярных выражений

Другой вероятный способ проверить, заканчивается ли строка другой подстрокой, — использовать регулярные выражения. Будьте осторожны с этим подходом, поскольку регулярные выражения обходятся дорого, и вы можете столкнуться с проблемами производительности.

Или используйте match() метод, который сопоставляет строку с регулярным выражением:

Это все, что касается определения того, заканчивается ли строка другой строкой в JavaScript.

Средний рейтинг 5 /5. Подсчет голосов: 21

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно

Источник

String.prototype.endsWith()

The endsWith() method determines whether a string ends with the characters of a specified string, returning true or false as appropriate.

Try it

Syntax

endsWith(searchString) endsWith(searchString, endPosition) 

Parameters

The characters to be searched for at the end of str . Cannot be a regex. All values that are not regexes are coerced to strings, so omitting it or passing undefined causes endsWith() to search for the string «undefined» , which is rarely what you want.

The end position at which searchString is expected to be found (the index of searchString ‘s last character plus 1). Defaults to str.length .

Return value

true if the given characters are found at the end of the string, including when searchString is an empty string; otherwise, false .

Exceptions

Description

This method lets you determine whether or not a string ends with another string. This method is case-sensitive.

Examples

Using endsWith()

const str = "To be, or not to be, that is the question."; console.log(str.endsWith("question.")); // true console.log(str.endsWith("to be")); // false console.log(str.endsWith("to be", 19)); // true 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 6, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

How to check if a string ends with a specific string or a character in JavaScript?

Another cool thing with this method is that you can define the end of the string instead of the default length of the string. For example, in the above example what if we don’t need to check till the ? character and only need to check if the string ends with the word you . You can do that by passing the length up to which you need to check as the second argument. Here we don’t need to check till the character ? . So let’s pass the length subtracted by one index as the second argument to the method like this,

// a string const str = "Hello, How are you?"; // check if string ends with the string "you" const doesIt = str.endsWith("you", str.length - 1); console.log(doesIt); // true 
  • the method accepts a string to check if it’s present at the end as the first argument.
  • the method accepts an optional length parameter to define the ending point for the string. If nothing is provided as the second argument, it defaults to the length property of the string.
  • the method returns a boolean true if string present at the end and false if not.

Источник

Javascript string ends with you

Last updated: Dec 20, 2022
Reading time · 3 min

banner

# Check if a String ends with a Substring in JavaScript

Use the endsWith() method to check if a string ends with a substring.

The endsWith method returns true if the string ends with the substring, otherwise, false is returned.

Copied!
const str = 'one two'; const substr = 'two'; if (str.endsWith(substr)) // 👇️ this runs console.log('✅ string ends with substring'); > else console.log('⛔️ string does NOT end with substring'); >

We used the String.endsWith method to check if a string ends with a specific substring.

The method returns true if the condition is met and false otherwise.

The endsWith() method performs a case-sensitive comparison. If you want to ignore the case, convert the string and the substring to lowercase.

Copied!
const str = 'one TWO'; const substr = 'two'; if (str.toLowerCase().endsWith(substr.toLowerCase())) // 👇️ this runs console.log('✅ string ends with substring'); > else console.log('⛔️ string does NOT end with substring'); >

Alternatively, you can use the String.indexOf() method.

# Check if a String ends with a Substring using indexOf()

This is a two-step process:

  1. Use the String.indexOf() method to check if the string contains the substring starting at a specific index.
  2. If the method doesn’t return -1 , the string ends with the substring.
Copied!
function endsWith(str, substr) return str.indexOf(substr, str.length - substr.length) !== -1; > console.log(endsWith('hello', 'llo')); // 👉️ true console.log(endsWith('hello', 'bye')); // 👉️ false console.log('hello'.length - 'llo'.length); // 👉️ 2

We used the String.indexOf method to check if a string ends with a substring.

The indexOf() method returns the index of the first occurrence of a substring in a string.

If the substring is not contained in the string, the method returns -1 .

We passed the following arguments to the method:

  1. search value — the substring to search for
  2. from index — from which index onwards to search for the substring in the string

We want to check if the string ends with the substring, so we subtract the substring’s length from the string’s length to get the from index.

# Check if a String ends with a Substring using Regex

Alternatively, you can use the RegExp.test() method.

The test method will return true if the string ends with the substring, otherwise, false is returned.

Copied!
const str = 'one two'; if (/two$/.test(str)) // 👇️ this runs console.log('✅ string ends with substring'); > else console.log('⛔️ string does NOT end with substring'); >

We used the RegExp.test method to check if a string ends with a specific substring.

The method returns true if the regular expression is matched in the string and false otherwise.

The dollar sign $ matches the end of the input.

In the example, we check if the string one two ends with the substring two .

If you want to make the regular expression case-insensitive, add the i flag.

Copied!
const str = 'one TWO'; if (/two$/i.test(str)) console.log('✅ string ends with substring'); > else console.log('⛔️ string does NOT end with substring'); >

The i flag allows us to perform a case-insensitive search in the string.

If you ever need help reading a regular expression, check out this regular expression cheatsheet by MDN.

It contains a table with the name and the meaning of each special character with examples.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью