- Проверьте, содержит ли строка только цифры
- 10 ответов
- JavaScript | Как получить только цифры из строки?
- Альтернативный синтаксис
- Как проверить, что строка состоит исключительно из цифр?
- Найти только цифры в строке javascript
- # Table of Contents
- # Check if a Character in String is a Number with Regex
- # Check if a Character in String is a Number using isNaN()
Проверьте, содержит ли строка только цифры
Я хочу проверить, содержит ли string только цифры. Я использовал это:
var isANumber = isNaN(theValue) === false; if (isANumber)
Но понял, что это также позволяет + и — . В общем, я хочу убедиться, что input содержит ТОЛЬКО цифры и никаких других символов. Поскольку +100 и -5 оба числа, isNaN() — неправильный путь. Возможно, регулярное выражение — это то, что мне нужно? Какие-нибудь советы?
10 ответов
c="123".match(/\D/) == null #true c="a12".match(/\D/) == null #false
Если строка содержит только цифры, она вернет ноль
Ну, вы можете использовать следующее регулярное выражение:
Вот решение без использования регулярных выражений:
function onlyDigits(s) < for (let i = s.length - 1; i >= 0; i--) < const d = s.charCodeAt(i); if (d < 48 || d >57) return false > return true >
Где 48 и 57 — коды символов для «0» и «9» соответственно.
Вот еще один интересный, читаемый способ проверить, содержит ли строка только цифры.
Этот метод работает путем разделения строки на массив с помощью оператор распространения, а затем использует every() , чтобы проверить, все ли элементы (символы) в массиве включены в строку цифр ‘0123456789’ :
const digits_only = string => [. string].every(c => '0123456789'.includes(c)); console.log(digits_only('123')); // true console.log(digits_only('+123')); // false console.log(digits_only('-123')); // false console.log(digits_only('123.')); // false console.log(digits_only('.123')); // false console.log(digits_only('123.0')); // false console.log(digits_only('0.123')); // false console.log(digits_only('Hello, world!')); // false
Хотя это вернет false для строк с начальными или конечными нулями.
JavaScript | Как получить только цифры из строки?
Нам нужно из этой строки удалить все буквы и оставить только символы и цифры. Как это сделать?
В этом нам помогут регулярные выражения, классы символов и диапазоны классов. Все замены мы будем производить методом replace() .
Регулярному выражению будет присвоен глобальный флаг «g» для оценки всех повторений в строке. Заменять мы будем на пустую строку, что будет приравнено к удалению.
Получим слипшиеся цифры в виде одной строки:
только пробелы stroka.replace(/[^0-9, ]/g,"") пробелы и любые другие символы stroka.replace(/[^0-9,\s]/g,"")
В диапазон символов мы добавили пробел, поэтому нам вернулась строка с пробелами.
Альтернативный синтаксис
Можно использовать специальный экранированный класс символа (CharacterClassEscape), который обозначается буквой D .
Он находит сопоставления в строке, которые НЕ равны набору из десяти цифр.
Он экранированный — это значит, что перед D мы должны будем поставить символ обратной косой черты \ . Ну и конечно это всё мы будем вводить внутри шаблона регулярного выражения, который обозначается границами в виде двух косых линий / / .
То есть мы можем найти в строке все места где символ не соответствует одному из: 0123456789
var stroka color: #993300;">Привет1274 ме234ня зо65вут 7987Ефим!"
stroka.replace(/\D/g,'') '1274234657987'
Как проверить, что строка состоит исключительно из цифр?
Как проверить что в строке все цифры, и вернуть false если в строке не все цифры?
const numberValidator = (val) => < let Reg = new RegExp("/^\d+$/"); return Reg.test(val); >;
Простой 14 комментариев
var num = prompt(''); // ввод числа alert(testNum(num)); // true — только цифры, false — нет function testNum(num) < if (isNaN(+num)) < return false >else < return true >> alert(typeof num) // num остался строкой
Артём Кан, строка из цифр- не то же самое, что число Javascript.
isNaN(«1.1»)
А уже тем более, приведение типов в JS, там очень много приколов
https://developer.mozilla.org/ru/docs/Web/JavaScri.
var num = prompt(''); alert(testNum(num)) function testNum(num)
alert выведет true только, если в num цифры и/или точка/- (123 , .0 , 123. ). (просто точка/минус — false)
Да, если точку и минус нужно гнать, то функция не катит.
Артём Кан, еще раз, нужно смотреть на задачу, в общем случае, строка из цифр абсолютно не является числом в JavaScript.
Виталий Архипов, Я вот что вспомнил. А что если сделать еще проверку переменной num на отрицательность и целостность? Как Вы считаете?
Артём Кан, если вы проверите, является ли строка целым неотрицательным числом, то получите проверку «Является ли строка натуральным числом».
Артём Кан, математически это верно, на практике в JS есть свои подводные камни, как я вам показал на примере с isNaN, особенно с приведением типов, переполнением и т.д.
9007199254740991 + 2 === 9007199254740991 + 1
Для задачи, определить состоит ли строка из цифр, самое правильно использовать регулярное выражение. Приведение строки в число JS — отдельная история.
Виталий Архипов, я не отрицаю, что на практике, конечно, лучше не использоваться этот способ, так как придется делать множество проверок. Но чисто интересно можно ли проверить так.
Найти только цифры в строке javascript
Last updated: Jan 2, 2023
Reading time · 3 min
# Table of Contents
# Check if a Character in String is a Number with Regex
Use the RegExp.test() method to check if a character in a string is a number.
The test() method will return true if the character is a valid number and false otherwise.
Copied!function isNumber(char) return /^\d$/.test(char); > const str = 'a1'; console.log(isNumber(str[0])); // 👉️ false console.log(isNumber(str[1])); // 👉️ true console.log(isNumber('100')); // 👉️ false console.log(isNumber('')); // 👉️ false console.log(isNumber(undefined)); // false
We used the RegExp.test method to test a regular expression against the character.
The forward slashes / / mark the start and end of the regular expression.
The caret ^ matches the beginning of the input and the dollar sign $ matches the end of the input.
The \d character matches any digit from 0 to 9.
If the character we pass to the function is a number, the isNumber() function returns true , otherwise, false is returned.
If you also want to return true for multiple characters if they are numbers, e.g. 100 , update the regular expression.
Copied!function isNumber(char) return /^\d+$/.test(char); > const str = 'a1'; console.log(isNumber(str[0])); // 👉️ false console.log(isNumber(str[1])); // 👉️ true console.log(isNumber('100')); // 👉️ true console.log(isNumber('')); // 👉️ false console.log(isNumber(undefined)); // false
We added the plus + special character to the regular expression.
The plus + matches the preceding item (a digit) 1 or more times.
In its entirety, the regular expression matches a string that starts with and ends with a digit and contains one or more digits.
Alternatively, you can use the isNan() function.
# Check if a Character in String is a Number using isNaN()
You can also use the isNan() function to check if a character is a number.
The function checks if the provided value is NaN (not a number). If the function returns false , then the character is a valid number.
Copied!function isNumber(char) if (typeof char !== 'string') return false; > if (char.trim() === '') return false; > return !isNaN(char); > const str = 'a1'; console.log(isNumber(str[0])); // 👉️ false console.log(isNumber(str[1])); // 👉️ true console.log(isNumber('123')); // 👉️ true console.log(isNumber('')); // 👉️ false console.log(isNumber(undefined)); // false
The isNumber() function returns true if the supplied string is a number and false otherwise.
We first check if the value passed to the function is not of type string , in which case we return false straight away.
Copied!if (typeof char !== 'string') return false; >
Then we check if the provided value is an empty string or contains only whitespace, in which case we also return false .
Copied!if (char.trim() === '') return false; >
Finally, we use the isNaN function to check if the provided character is not a number.
The logical NOT (!) operator is used to negate the value returned from the isNaN (is not a number) function.
The isNaN function tries to convert the string to a number and returns true if it fails.
Copied!console.log(isNaN('a')); // 👉️ true console.log(isNaN('')); // 👉️ false console.log(isNaN(' ')); // 👉️ false
This seems quite confusing at first, but the isNaN function converts an empty string or a string containing spaces to a number (0), so it returns false .
Copied!console.log(Number('')); // 👉️ 0 console.log(Number(' ')); // 👉️ 0
This is why we used the trim() method — to trim the string and verify that it’s not an empty string.
We know that if the isNaN function gets called with a string that contains at least 1 character and returns true , then the string is NOT a valid number.
Conversely, if the isNaN function gets called with a string that contains at least 1 character and returns false , then the string is a valid number.
Here are some more examples of calling isNaN() with strings.
Copied!console.log(isNaN('123')); // 👉️ false console.log(isNaN('1.23')); // 👉️ false console.log(isNaN('1,23')); // 👉️ true console.log(isNaN('123test')); // 👉️ true
Which approach you pick is a matter of personal preference. I’d use the RegExp.test() method because I find it more direct and intuitive.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.