Extracting numbers in a string in javascript - javascript

My app reads excel from a user. The app will receive "Quantity and Unit" of an item.
For Example,
5pcs.
12oz.
5lb.
I would like to get the number and store it in var qu[0].
I would like to get the string and store it in var qu[1].
How can i do it? I tried split. but only the number is taken.

You can get the number with an regular expression an the following pattern:
^(\d*)(.*)$
How to use regular expressions in Javascript

alert(Number("45a".match(/\d*/)) + 1)
https://jsfiddle.net/zep0tu0b/

Use parseInt or parseFloat to extract the number.
Then the remaining part should be the unit.
var num = parseFloat(str),
unit = str.substr(num.toString().length);
Consider checking if num is NaN, and then set unit to something else.

Related

js get result of 2 or more numbers with mathematical expressions

I have a counting-Discord bot which works perfectly fine, but i want to add some specials. Users should can use mathematical expressions like +;-;/;*, but i can't get the result of the string
example:
console.log(+"14+2") or console.log(Number.parseInt(+"1+3*5-1"))
all equals NaN or just the first number.
i just found on another stackoverflow question how i can if it's a number like true and false, but not the result.
You could just use math.js:
console.log(math.evaluate("14+2"))
console.log(math.evaluate("1+3*5-1"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/11.0.1/math.js"></script>
You're adding strings and expecting a number result. You can't convert a string like "14 + 2" into an expression.
The methods you've described are valid, but they can only convert a string into a number, not a complete expression.
So, you can do something like this:
const result = Number("14") + Number ("2");
Which is effectively the same as this:
const result = +"14" + +"2"
Or this:
const result = Number.parseInt("14") + Number.parseInt("2")
But I think that the Number() method is a little more readable than either.
To get your input into the correct syntax, you may need to use something like string.Split()

How can I use JavaScript's replace function to divide a matched number by 100?

I am trying to divide a regex-matched number in string format by 100 within JavaScript's replace function:
var number = "4354543";
var result = number.replace(/(\d+)/, '$1/100');
console.log(result); -> Printing 4354543/100
The answer should be 43545.43, but instead I'm getting "4354543/100".
Is it possible to achieve this?
You can use regular expressions for this, if that's what you're really after - for instance, lets say you want to divide numbers in a larger string by 100. To do this, you have to use the function callback, which lets you manipulate the captured groups in more complex ways:
var number = "abc 4354543 xyz";
var result = number.replace(/\d+/g, function(val) {
return +val/100;
});
console.log(result); //abc 43545.43 xyz
If you know that the input strings are at least 3 digits, a simple solution is to insert a decimal separator before the last 2 digits.
var number = "4354543";
var result = number.replace(/(\d+)(\d{2})/, '$1.$2');
console.log(result);
However, using a function as the second argument to .replace, as the answer by James Thorpe does, gives you more flexibility.
I think there is some confusion in your mind about what regex can do.
In your case you really don't need regex. Just do
var number = "4354543";
console.log(number/100);
You will see what you expect, js will change string to number(don't worry)
Regexp are not suitable for mathematic operations.
Use Number javascript class.
In your case
const number = '5485454845'; // Wathever
const result = Number(number) / 100;

Jquery Regex to fetch number after $ symbol

Hi I am trying to write a small script which gets all the amounts in a page(Amazon).
This is what I have come up with to store the values in an array.
var amounts= $('*').text().match(/^\$[-0-9.,]*/);
But this code is not working because in the actual page there is some text/tags before the $ symbol like
<p>$500</p>
Can someone pls correct my code?
I've had luck with this on amazon
var arrayPrices = document.body.textContent.match(/\$\d+\.?\d+/g);
str.match(/^\$[-0-9.,]*/) could be
var arr=str.match/\$\d+(\.\d+)?/g
To match all the integers and (possible) decimal strings that follow a dollar sign.
you can use reggae grouping like this
var str = "$500";
var array = "/\$(\d+)/".exec(str);
alert(array[1]);
in array[0] you will find the String str. In array[1] the first hit and so on.

Format number using RegExp in javascript

I have a number like below
var number = '12345678904444'
and i want like this
(123) 456-7890x4444
Format is (###) ###-####x####.
How can i achieve this.
For what it's worth, this is what RegExp solution would look like ;-)
number.replace(/^(\d{3})(\d{3})(\d{4})(\d{4})$/, '($1) $2-$3x$4.');
You can use the javascript string split method :
var number = '12345678904444';
var numbers_array = numbers.split("");
Then you can use the array of the numbers to create a new string, following the format you want.
I'm sure you can do that !
If you want to format a number in Javascript, your best bet is to use String.slice() to extract the number parts you need, then contact them together using +.
DO NOT USE REGEX FOR THIS!! If your string in this has an error and can't be parsed properly, you run the risk of catastrophic backtracking, where your processing lasts really, really long.
I would prefer this:
var num = '1234567890x4444';
var first = num.substr(0,3), second = num.substr(3,3), last = num.substr(6);
var formatted = '('+first+') ' + second + '-'+ last;
Result:
console.log(formatted); // (123) 456-7890x4444

How to check if a string contains a number in JavaScript?

I don't get how hard it is to discern a string containing a number from other strings in JavaScript.
Number('') evaluates to 0, while '' is definitely not a number for humans.
parseFloat enforces numbers, but allow them to be tailed by abitrary text.
isNaN evaluates to false for whitespace strings.
So what is the programatically function for checking if a string is a number according to a simple and sane definition what a number is?
By using below function we can test whether a javascript string contains a number or not. In above function inplace of t, we need to pass our javascript string as a parameter, then the function will return either true or false
function hasNumbers(t)
{
var regex = /\d/g;
return regex.test(t);
}
If you want something a little more complex regarding format, you could use regex, something like this:
var pattern = /^(0|[1-9][0-9]{0,2}(?:(,[0-9]{3})*|[0-9]*))(\.[0-9]+){0,1}$/;
Demo
I created this regex while answering a different question awhile back (see here). This will check that it is a number with atleast one character, cannot start with 0 unless it is 0 (or 0.[othernumbers]). Cannot have decimal unless there are digits after the decimal, may or may not have commas.. but if it does it makes sure they are 3 digits apart, etc. Could also add a -? at the beginning if you want to allow negative numbers... something like:
/^(-)?(0|[1-9][0-9]{0,2}(?:(,[0-9]{3})*|[0-9]*))(\.[0-9]+){0,1}$/;
There's this simple solution :
var ok = parseFloat(s)==s;
If you need to consider "2 " as not a number, then you might use this one :
var ok = !!(+s==s && s.length && s.trim()==s);
You can always do:
function isNumber(n)
{
if (n.trim().length === 0)
return false;
return !isNaN(n);
}
Let's try
""+(+n)===n
which enforces a very rigid canonical way of the number.
However, such number strings can be created by var n=''+some_number by JS reliable.
So this solution would reject '.01', and reject all simple numbers that JS would stringify with exponent, also reject all exponential representations that JS would display with mantissa only. But as long we stay in integer and low float number ranges, it should work with otherwise supplied numbers to.
No need to panic just use this snippet if name String Contains only numbers or text.
try below.
var pattern = /^([^0-9]*)$/;
if(!YourNiceVariable.value.match(pattern)) {//it happen while Name Contains only Charectors.}
if(YourNiceVariable.value.match(pattern)) {//it happen while Name Contains only Numbers.}
This might be insane depending on the length of your string, but you could split it into an array of individual characters and then test each character with isNaN to determine if it's a number or not.
A very short, wrong but correctable answer was just deleted. I just could comment it, besides it was very cool! So here the corrected term again:
n!=='' && +n==n'
seems good. The first term eliminates the empty string case, the second one enforces the string interpretataion of a number created by numeric interpretation of the string to match the string. As the string is not empty, any tolerated character like whitespaces are removed, so we check if they were present.

Categories