JavaScript count digits in a string [duplicate] - javascript

This question already has answers here:
Count the number of integers in a string
(6 answers)
Closed 1 year ago.
I want to know how many digits 0 to 9 are in a string:
"a4 bbb0 n22nn"
The desired answer for this string is 4.
My best attempt follows. Here, I'm iterating through each char to check if it's a digit, but this seems kind of heavy-handed. Is there a more suitable solution?
const str = 'a4 bbb0 n22nn'
const digitCount = str.split('').reduce((acc, char) => {
if (/[0-9]/.test(char)) acc++
return acc
}, 0)
console.log('digitCount', digitCount)

With the regular expression, perform a global match and check the number of resulting matches:
const str = 'a4 bbb0 n22nn'
const digitCount = str.match(/\d/g)?.length || 0;
console.log('digitCount', digitCount)

Related

how to find the first number from string in js(javascript)? [duplicate]

This question already has answers here:
Get the first integers in a string with JavaScript
(5 answers)
Closed 6 months ago.
How to find the first number from string in javascript?
var string = "120-250";
var string = "120,250";
var string = "120 | 250";
Here is an example that may help you understand.
Use the search() method to get the index of the first number in the string.
The search method takes a regular expression and returns the index of the first match in the string.
const str = 'one 2 three 4'
const index = str.search(/[0-9]/);
console.log(index); // 4
const firstNum = Number(str[index]);
console.log(firstNum); // 2
Basic regular expression start of string followed by numbers /^\d+/
const getStart = str => str.match(/^\d+/)?.[0];
console.log(getStart("123,456"));
console.log(getStart("123-456"));
console.log(getStart("123|456"));
console.log(getStart("xxx,xxx"));
Or parseInt can be used, but it will drop leading zeros.
const getStart = str => parseInt(str, 10);
console.log(getStart("123,456"));
console.log(getStart("123-456"));
console.log(getStart("123|456"));
console.log(getStart("xxx,xxx"));

Using Regex as conditional in Javascript [duplicate]

This question already has answers here:
How to check if character is a letter in Javascript?
(17 answers)
Closed 3 years ago.
Hello I am having trouble trying to use Regex to check if each character in string is an alphabet.
First let me introduce the problem itself.
There is a string mixed with special chars and alphabets and suppose to return the number of alphabets only.
My code/pseudo code for problem is :
//Create var to hold count;
var count = 0;
//Loop thru str
for(let char of str){
//Check if char is a alphabet
***if(char === /[A-Za-z]/gi){***
//if so add to count
count ++;
}
//return count;
return count;
}
How can I use Regex in a conditional statement to check if each char is an alphabet????
Please help!
const pattern = /[a-z]/i
const result = [...'Abc1'].reduce((count,c) => pattern.test(c) ? count+1 : count, 0)
console.log(result) // 3

Typescript/Javascript - Parse float with comma as decimal separator [duplicate]

This question already has answers here:
Parsing numbers with a comma decimal separator in JavaScript
(3 answers)
javascript parseFloat '500,000' returns 500 when I need 500000
(7 answers)
Closed 3 years ago.
I have the following string:
const NumberAsString = "75,65";
And I need to parse it as float like this:
Amount: parseFloat(NumberAsString);
I've seen some post that suggested to replace the comma with a dot which works well when the comma is used as thousand separator. But in this case the comma is used as decimal separator If I replace it I get this number: 7.565,00 which is not my number 75.65. Is there any way to parse this number to float without changing it's value?
PD: In my system I have a helper that takes the numbers with the dot as thousand separator and the comma as decimal separator. I cannot avoid this.
Here is a clunky way of doing it.
Using an array and reduce
const tests = ['70,65', '7,000,01', '700'];
const parseNumber = (num) => {
if(num === undefined) return undefined;
if(num.indexOf(',') < 0) return parseFloat(num);
const numArr = num.split(',');
return parseFloat( numArr.reduce((a, v, i) => a + ((i === numArr.length - 1) ? `.${v}` : v), '') );
};
tests.forEach(t => console.log(parseNumber(t)));

RegEx for checking multiple matches [duplicate]

This question already has answers here:
How can I match overlapping strings with regex?
(6 answers)
Closed 3 years ago.
I want to match all occurrence in string.
Example:
pc+pc2/pc2+pc2*rr+pd
I want to check how many matched of pc2 value and regular expression is before and after special character exists.
var str = "pc+pc2/pc2+pc2*rr+pd";
var res = str.match(new RegExp("([\\W])pc2([\\W])",'g'));
But I got only +pc2/ and +pc2* and /pc2+ not get in this.
Problem is in first match / is removed. So after that, it is starting to check from pc2+pc2*rr+pd. That's why /pc2+ value does not get in the match.
How do I solve this problem?
You need some sort of recursive regex to achieve what you're trying to get, you can use exec to manipulate lastIndex in case of value in string is p
let regex1 = /\Wpc2\W/g;
let str1 = 'pc+pc2/pc2+pc2*rr+pd';
let array1;
let op = []
while ((array1 = regex1.exec(str1)) !== null) {
op.push(array1[0])
if(str1[regex1.lastIndex] === 'p'){
regex1.lastIndex--;
}
}
console.log(op)

Check whether an input string contains a (signed) number [duplicate]

This question already has answers here:
Regular expression for floating point numbers
(20 answers)
Closed 4 years ago.
I want to check if my input string contains numbers and display an array of these numbers. The number is composed of an optional sign (- or +), one or more consecutive digits and an optional fractional part. The fractional part is composed of a dot . followed by zero or more digits.
For example f2('a1 12 13.b -14.5+2') : returns [1, 12, 13, -14.5, 2]
I try this code from a response here
function f2(input) {
let str = String(input);
for (let i = 0; i < str.length; i++) {
console.log(str.charAt(i));
if (!isNaN(str.charAt(i))) {
//if the string is a number, do the following
return str.charAt(i);
}
}
}
let result = f2("a1 12 13.b -14.5+2");
console.log(result);
You can easily use a regex expression to match the numbers in the string:
function f2(input) {
let str = String(input);
let result = str.match(/\-?\d+\.\d+|\-?\d+/g)
return result
}
let result = f2("a1 12 13.b -14.5+2");
console.log(result);

Categories

Resources