I'm trying to find out how to get numbers that are in a string.
I tried the Number(string) function but it returns me a "NaN" ...
For example :
let str = "MyString(50)";
/*Function that return "NaN"*/
let numbers = Number(str);
console.log(numbers);
//Output expected : 50
//Output if get : 50
Do anyone has an idea why "Number" isn't returning me the right value or another way to do it ?
Thanks for answers.
You can use String.match with a regex to filter out numbers, and use unary + or Number(str) or parseInt to get the number
let str = "MyString(50)";
let numbers = +str.match(/\d+/);
console.log(numbers);
The match regular expression operation is used to get number.
var str = "MyString(50)";
var matches = str.match(/(\d+)/);
console.log(matches[0]);
Refer this link to know about regular expression link [https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions].
Here a more comprehensive regex to detect all kinds of numbers in a string:
/ 0[bB][01]+ | 0[xX][0-9a-fA-F]+ | [+-]? (?:\d*\.\d+|\d+\.?) (?:[eE][+-]?\d+)? /g;
binary | hex | sign? int/float exponential part?
const matchNumbers = /0[bB][01]+|0[xX][0-9a-fA-F]+|[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g;
let str = `
Let -1
us +2.
start -3.3
and +.4
list -5e-5
some +6e6
number 0x12345
formats 0b10101
`;
console.log("the string", str);
const matches = str.match(matchNumbers);
console.log("the matches", matches);
const numbers = matches.map(Number);
console.log("the numbers", numbers);
.as-console-wrapper{top:0;max-height:100%!important}
Related
Does anyone know how to make a number from a string with comma separators, in JS.
I got: "23,21" and I want to get it as a number value.
"23,21" --> 23,21
You can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
But before you need to replace comma for dot.
parseFloat('23,21'.replace(/,/, '.')); // == 23.21
let x = '16,5';
parseFloat(x.replace(/,/, '.')); // == 16.5
You can but not with the "comma" (,). In some countries people do use commas instead of dots to write decimals. If that's the case then what you can do is:
let a = "23,25";
let b = a.replaceAll(',', '.');
console.log(parseFloat(b));
But doing the this with the comma is also not wrong. But you will only get the part before the decimal.
i.e. 23 in your case
Check if you want this.
var str = '23,21';
console.log((str.split(",").map((i) => Number(i))));
UPDATE
var str = '23,21';
var arr = str.split(",").map((i) => Number(i));
console.log(parseFloat(arr.join('.')));
This is my equation
5x^2 + 3x - 5 = 50
I have used this regex
/([+|-])([1-9][a-z])+|([1-9][a-z])+|([+|-])([1-9])+|([1-9])+/mg
but it does not give the results I want.
I want to divide my equation like this
array(
5x^2 ,
3x ,
-5 ,
=50
)
As a starting point, you could split your string by several mathematical operator symbols (for instance +, -, *, / and =). Then you get an array of terms but without the operators that were used to split the string:
const string = "5x^2 + 3x - 5 = 50";
const regex = /\+|\-|\*|\/|=/g;
const result = string.split(regex);
console.info(result);
To retrieve the delimiter characters as well, have a look at this StackOverflow post for example.
First remove the whitespaces.
Then match optional = or - followed by what's not = or - or +
Example snippet:
var str = "5x^2 + 3x - 5 = 50";
let arr = str
.replace(/\s+/g, '')
.match(/[=\-]*[^+=\-]+/g);
console.log(arr);
I have string like "17,420 ฿". How to change this as integer value. I have done
var a = "17,420 ฿"
var b = a.split(' ')[0];
console.log(Number(b))
But I am getting NaN because of ,.
So i have done like below
var c = b.replace( /,/g, "" );
console.log(Number(c));
Now, I am getting 17420 as an integer.
But, is there any better method to do it.
You could start by stripping off anything that's NOT a number or a decimal point. string.replace and a bit of RegExp will help. Then use parseFloat or Number to convert that number-like string into a number. Don't convert to an integer (a decimal-less number), since you're dealing with what appears to be currency.
const num = parseFloat(str.replace(/[^0-9.]/g, ''))
But then at the end of the day, you should NOT be doing string-to-number conversion. Store the number as a number, then format it to a string for display, NOT the other way around.
You can easily remove all non-digits with a regex like so:
a.replace(/\D/g, '');
Then use parseInt to get integer value:
parseInt(b);
Combined:
var result = parseInt(a.replace(/\D/g, ''));
You can use parseInt after removing the comma
var a = "17,420 ฿"
console.log(parseInt(a.replace(",",""), 10))
o/p -> 17420
Number(a.replace(/[^0-9.]/g, ""))
This will replace all not numbers chars... is that helpful?
Split for the , and then join via . and then parse it as a float. Use .toFixed() to determine how many decimal places you wish to have.
console.log(
parseFloat("17,420 ฿".split(' ')[0].split(',').join('.')).toFixed(3)
);
As a function:
const convert = (str) => {
return parseFloat(str.split(' ')[0].split(',').join('.')).toFixed(3)
}
console.log(convert("17.1234 $"));
console.log(convert("17 $"));
console.log(convert("17,2345 $"));
Alternative:
const convert = (str) => {
let fixedTo = 0;
const temp = str.split(' ')[0].split(',');
if(temp.length > 1){
fixedTo = temp[1].length;
}
return parseFloat(temp.join('.')).toFixed(fixedTo)
}
console.log(convert("17,1234 $"));
console.log(convert("17,123 $"));
console.log(convert("17,1 $"));
console.log(convert("17 $"));
I cannot understand what this little snippet: var num = str.replace(/[^0-9]/g, ''); does.
Context:
function retnum(str) {
var num = str.replace(/[^0-9]/g, '');
var liczba = parseInt(num);
return liczba;
}
This JavaScript snippet will rip out anything that is not (the ^ part of the regular expression means "not") a number in str and then return an integer cast from the result as liczba. See my comments:
// This function will return a number from a string that may contain other characters.
// Example: "1.23" -> 123
// Example: "a123" -> 123
// Example: "hg47g*y#" -> 47
function retnum(str) {
// First let's replace everything in str that is not a number with "" (nothing)
var num = str.replace(/[^0-9]/g, '');
// Let's use JavaScript's built in parseInt() to parse an Integer from the remaining string (called "num")
var liczba = parseInt(num);
// Let's now return that Integer:
return liczba;
}
By the way, "liczba" means number in Polish :-)
This function takes a string, strips all non-number characters from it, turns the string into an integer, and returns the integer. The line you're asking about specifically is the part that strips out all non-number characters from the initial string, using the string.replace method.
It's not obfuscated, it's using a regular expression.
The expression matches all things which are not numbers then removes them. 0-9 means "any digit" and the ^ means "not". The g flag means to check the entire string instead of just the first match. Finally, the result is converted to a number.
Example:
var input = 'abc123def456';
var str = input.replace(/[^0-9]/g, '');
var num = parseInt(str);
document.querySelector('pre').innerText = num;
<pre></pre>
It literally just replaces anything which is not a number with a blank ('').
i have a id like stringNumber variable like the one as follows : example12
I need some javascript regex to extract 12 from the string."example" will be constant for all id and just the number will be different.
This regular expression matches numbers at the end of the string.
var matches = str.match(/\d+$/);
It will return an Array with its 0th element the match, if successful. Otherwise, it will return null.
Before accessing the 0 member, ensure the match was made.
if (matches) {
number = matches[0];
}
jsFiddle.
If you must have it as a Number, you can use a function to convert it, such as parseInt().
number = parseInt(number, 10);
RegEx:
var str = "example12";
parseInt(str.match(/\d+$/)[0], 10);
String manipulation:
var str = "example12",
prefix = "example";
parseInt(str.substring(prefix.length), 10);