Javascript ends with number

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

Читайте также:  Java context lookup java comp env

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 String Ends with Number in Javascript

In this tutorial, you will learn how to check if string ends with number in javascript. A number is formed by the combination of digits from 0 to 9. From a developer perspective, it can be a bit tricky to find if a string ends with a number.

There are numerous ways to check if a string ends with a number. But for the sake of simplicity, we will use the length property, charAt() method, regular expression, and ternary operator ( ? ) to accomplish our goal. The length property returns the length of the string. If the string is empty, then it will return 0.

The test( ) method of RegExp object is used to perform a pattern search in a string and returns a Boolean value. A string consists of multiple characters and these characters in a string have a 0-based index. That means the first character in a string has an index of 0 and to get that character by index, we can use charAt() method.

In the following example, we have one global variable that holds a string. Upon click of a button, we will check if the string ends with a number and display the result on the screen. Please have a look over the code example and the steps given below.

  • We have 3 elements in the HTML file ( div , button , and h1 ). The div element is just a wrapper for the rest of the elements.
  • The innerText for the button element is “Check” and for the h1 element, it is “Result” .
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
  • We have selected the button element and h1 element using the document.querySelector() method and stored them in btnCheck and output variables respectively.
  • We have attached a click event listener to the button element.
  • We have a global variable myString which holds a string as its value.
  • We have the regExp variable which holds a regular expression /\d/ as its value to match numbers.
  • In the event handler function, we are getting the last character from string using charAt() method. By subtracting 1 from the length property, we are passing index of the last character to the charAt() method. The last character is stored in the lastChar variable.
  • We are calling the test() method of regExp and passing lastChar as a parameter. It will return a Boolean value which we are storing in the found variable.
  • We are using the ternary operator ( ? ) and checking whether found is true or false. If it is true, that means the string ends with a number.
  • Depending upon the result of the check, we will assign “Yes” or “No” to the result variable.
  • We are displaying the result in the h1 element using the innerText property.
let btnCheck = document.querySelector("button"); let output = document.querySelector("h1"); let myString = "The number is 587"; let regExp = /\d/; btnCheck.addEventListener("click", () => < let lastChar = myString.length - 1; let found = regExp.test(lastChar) let result = found ? "Yes" : "No"; output.innerText = result; >);

Источник

Check if a string ends with number in JavaScript

If we want to check if a text ends in a number, we unfortunately cannot use the endsWith method because it only checks for a specific case. In this case, you need to check that the last character in the text is between 0 and 9. To solve this problem we can use a regular expression and the test method.

The test() method executes a search for a match between a regular expression and a specified string. Returns true or false.

In this case the regular expression is quite simple. We only need to check if the last character $ is a digit \d or not: /\d$/

  • Count the number of characters in a string with JavaScript
  • Concatenate strings in JavaScript
  • Convert array to comma separated string using JavaScript
  • Check if string ends with slash using JavaScript
  • Get the last character of a string in JavaScript
  • Remove spaces from string at the beginning, end, or both in JavaScript
  • Remove all extra spaces from a string in JavaScript
  • Check if string contains a specific character using JavaScript
  • Remove protocol from URL with JavaScript
  • Remove emojis from a string with JavaScript
  • Check if a string ends with number in JavaScript
  • Remove specific character from a string in JavaScript
  • Remove the last character from a string in JavaScript
  • Count the number of words in a string using JavaScript
  • Count the number of lines in a string in JavaScript
  • Convert string to int in JavaScript
  • Convert string to lowercase with JavaScript
  • Capitalize words in a string using JavaScript
  • Generate random string in JavaScript
  • Generate UUID in JavaScript
  • Generate random color with JavaScript
  • Convert string to kebab case in JavaScript
  • Convert snake case to camel case in JavaScript
  • Convert string to character array in JavaScript
  • Convert camel case to snake case in JavaScript
  • Remove accents from a string in JavaScript
  • Convert a string to sentence case in JavaScript
  • Convert string to title case in JavaScript
  • Convert string to snake case in JavaScript
  • Convert string to pascal case in JavaScript
  • Convert string to camel case in JavaScript
  • Convert string to uppercase with JavaScript
  • Convert object to JSON string in JavaScript
  • Parse JSON string in JavaScript
  • convert number to string in JavaScript
  • Use colors in JavaScript console
  • Get string length in JavaScript
  • Split a string into words
  • Replace line break with br in JavaScript
  • Replace spaces with dashes in JavaScript
  • Create multiline string in JavaScript

Источник

Javascript ends with number

Last updated: Jan 2, 2023
Reading time · 4 min

banner

# Parse a String with Commas to a Number using String.replaceAll()

To parse a string with commas to a number:

  1. Use the replaceAll() method to remove all the commas from the string.
  2. The replaceAll method will return a new string containing no commas.
  3. Use the parseFloat() function to convert the string to a number.
Copied!
const str = '12,000,000.50'; const num = parseFloat(str.replaceAll(',', '')); console.log(num); // 👉️ 123000000.5

The String.replaceAll() method returns a new string with all matches of a pattern replaced by the provided replacement.

The method takes the following parameters:

Name Description
pattern The pattern to look for in the string. Can be a string or a regular expression.
replacement A string used to replace the substring match by the supplied pattern.

The String.replaceAll() method returns a new string with the matches of the pattern replaced. The method doesn’t change the original string.

Strings are immutable in JavaScript.

The last step is to call the parseFloat() function with the result.

The parseFloat function parses the provided string and returns a floating-point number.

If the parseFloat() function cannot convert the string to a number, because the string contains non-numeric characters, the method returns NaN (not a number).

Here are some examples of using the parseFloat() function.

Copied!
console.log(parseFloat('100')); // 👉️ 100 console.log(parseFloat('100abc')); // 👉️ 100 console.log(parseFloat('100.5')); // 👉️ 100.5 console.log(parseFloat(10.5)); // 👉️ 10.5 console.log(parseFloat('a123')); //👉️ NaN

If you have to do this often, define a reusable function.

Copied!
function parseToNumber(str) return parseFloat(str.replaceAll(',', '')); > console.log(parseToNumber('12,000,000.50')); // 👉️ 12000000.5 console.log(parseToNumber('12,123,456')); // 👉️ 12123456

The function takes a string with commas as thousands separator and parses the string to a number.

# Parse a String with Commas to a Number using String.split()

This is a three-step process:

  1. Use the split() method to split the string on each comma.
  2. Use the join() method to join the array into a string.
  3. Use the parseFloat() function to convert the string to a number.
Copied!
function parseToNumber(str) return parseFloat(str.split(',').join('')); > console.log(parseToNumber('12,000,000.50')); // 👉️ 12000000.5 console.log(parseToNumber('12,123,456')); // 👉️ 12123456

The String.split() method takes a separator and splits the string into an array on each occurrence of the provided delimiter.

Copied!
const str = '12,000,000.50'; // 👇️ [ '12', '000', '000.50' ] console.log(str.split(','));

The String.split() method takes the following 2 parameters:

Name Description
separator The pattern describing where each split should occur.
limit An integer used to specify a limit on the number of substrings to be included in the array.

We split the string on each comma and joined the array without a separator.

The Array.join() method concatenates all of the elements in an array using a separator.

The only argument the Array.join() method takes is a separator — the string used to separate the elements of the array.

If the separator argument is set to an empty string, the array elements are joined without any characters in between them.

Copied!
const str = '12,000,000.50'; // 👇️ 12000000.50 console.log(str.split(',').join(''));

The last step is to pass the result to the parseFloat() function to convert the string to a number.

# Parse a String with Commas to a Number using String.replace()

This is a three-step process:

  1. Use the replace() method to remove all the commas from the string.
  2. The replace method will return a new string containing no commas.
  3. Convert the string to a number.
Copied!
const str = '12,000,000.50'; const num = parseFloat(str.replace(/,/g, '')); console.log(num); // 👉️ 123000000.5

The String.replace() method returns a new string with one, some, or all matches of a regular expression replaced with the provided replacement.

The method takes the following parameters:

Name Description
pattern The pattern to look for in the string. Can be a string or a regular expression.
replacement A string used to replace the substring match by the supplied pattern.

The forward slashes / / mark the beginning and end of the regular expression.

We only match a comma in the regular expression.

Copied!
const str = '12,000,000.50'; const num = parseFloat(str.replace(/,/g, '')); console.log(num); // 👉️ 123000000.5

The g (global) flag is used to match all occurrences of a comma in the string and not just the first occurrence.

We used an empty string for the replacement for each match to remove all commas from the string.

The last step is to use the parseFloat() function to convert the string to a number.

Which approach you pick is a matter of personal preference. I’d use the String.replaceAll() method as I find it quite direct and intuitive.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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

Источник

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