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

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);

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"));

JavaScript count digits in a string [duplicate]

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)

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)));

splitting a string with a decimal number and some characters [duplicate]

This question already has answers here:
Splitting a string at special character with JavaScript
(8 answers)
How do I split a string, breaking at a particular character?
(17 answers)
Closed 4 years ago.
I have strings like:
'1234picas'
'1234 px'
'145.4us'
I want to split them in two parts: the numeric part and the non numeric one. For example: '1234.4us' need to be splitted in '1234.4' and 'us'. I am tempted to insert a separator between the last digit and the non numeric and use split but is there a better way to do this in JavaScript
Thanks
Note: this is not the slitting of a string at special char. it could be converted to that but this is what I am trying to avoid.
You can do it using String.prototype.match():
const a = '1234picas';
const b = '1234 px';
const c = '145.4us';
function split(input) {
const splitArray = input.match(/([\d\.]+)(.*)/); // match only digits and decimal points in the first group and match the rest of the string in second group
return {
numeric: splitArray[1],
nonnumeric: splitArray[2],
};
}
console.log(split(a));
console.log(split(b));
console.log(split(c));
Regex explanation | Regex101
You can use .split with a regex using a lookahead:
str.split(/(?=[^\d.-])/g))
.map(y => [
y[0],
y.slice(1).join('').trim()
])
x = ["1234picas", "1234 px", "145.4us"];
console.log(x.map(y =>
y.split(/(?=[^\d.-])/g))
.map(y => [
y[0],
y.slice(1).join('').trim()
])
)
You can do like this in javascript to split:
var myString = '145.4us';
var splits = myString.split(/(\d+\.?\d+)/);
console.log(splits);
here's one way to do it using parseFloat() and slice() , you can add it to the Sting.prototype if you want :
const str1 = '1234picas',
str2 = '1234 px',
str3 = '145.4us';
String.prototype.split = function () {
const num = parseFloat(this);
const alph = this.slice(num.toString().length, this.length)
return {
num,
alph
}
}
console.log(str1.split());
console.log(str2.split());
console.log(str3.split());
This may help you:
var a = "4343.453fsdakfjdsa";
a.match(/[a-zA-Z]+|[\d\.?]+/ig);
MDN for String.match
It basically says match the alphabetical letters OR match numbers with an optional period. The ig is insensitive (which is not really needed) and global as in don't return on the first match, keep going until all of the string has been parsed.
Regex!
Here is how it works: https://regex101.com/r/XbI7Mq/1
const test = ['1234picas', '1234 px', '145.4us', 'no'];
const regex = /^(\d+\.?\d+)\s?(.*)/;
test.forEach(i => {
const result = regex.exec(i);
if (result) {
console.log(result[1], result[2])
}
});

Categories

Resources