get number only in javascript [duplicate] - javascript

This question already has answers here:
How can I extract a number from a string in JavaScript?
(27 answers)
Closed 9 years ago.
I have a string likes
AA-12,AB-1,AC-11,AD-8,AE-30
I want to get number only from this string likes
12,1,11,8,30
How can I get this using JavaScript ? Thanks :)

Use a regex, eg
var numbers = yourString.match(/\d+/g);
numbers will then be an array of the numeric strings in your string, eg
["12", "1", "11", "8", "30"]

Also if you want a string as the result
'AA-12,AB-1,AC-11,AD-8,AE-30'.replace(/[^0-9,]/g, '')

var t = "AA-12,AB-1,AC-11,AD-8,AE-30";
alert(t.match(/\d+/g).join(','));
Working example: http://jsfiddle.net/tZQ9w/2/

if this is exactly what your input looks like, I'd split the string and make an array with just the numbers:
var str = "AA-12,AB-1,AC-11,AD-8,AE-30";
var nums = str.split(',').map(function (el) {
return parseInt(el.split('-')[1], 10);
});
The split splits the string by a delimiter, in this case a comma. The returned value is an array, which we'll map into the array we want. Inside, we'll split on the hyphen, then make sure it's a number.
Output:
nums === [12,1,11,8,30];
I have done absolutely no sanity checks, so you might want to check it against a regex:
/^(\w+-\d+,)\w+-\d+$/.test(str) === true
You can follow this same pattern in any similar parsing problem.

Related

Compare two strings in JS to see if the first big string contains exact same match or not [duplicate]

This question already has answers here:
How do I find an exact word in a string?
(5 answers)
Closed 28 days ago.
I want to compare the following two variables to see if they match exactly or not.
What I am doing right now is:
var string1 = "S1";
var string2 = "LS1 B26 M90";
let result = string2.indexOf(string1);
It returns 1 which means S1 exists in string2. I want it to look for "S1" and not to match with "LS1".
you can simply achive by below:
String("LS1 B26 M90").split(" ").includes("LS1")
String("LS1 B26 M90").split(" "): convert string into string list.
.includes("LS1"): will check the existence it return true in case of
match otherwise false.

How to convert string to number? [duplicate]

This question already has answers here:
Javascript: Converting String to Number?
(4 answers)
Closed 4 years ago.
How to convert "4,250,000.40" to 4,250,000.40 that is converting string to number by remaining the commas and dots? using JavaScript
You can use parseFloat(str) to convert a string to a number, but first you need to remove the commas from the string, as parseFloat doesn't work for numbers with commas in them.
parseFloat(str.replace(/,/g, ""));
var str = "4,250,000.40";
str = str.replace(/\,/g, "")
console.log(str)
console.log(parseFloat(str).toFixed(2))//to always show 2 decimal places
You can't directly convert "4,250,000.40" to a number in vanilla JS, let alone preserve commas. 4,250,000.40 is not a valid number in JavaScript, because a comma is an illegal character in a Number.
you can use regex to delete commas, then use Number.parseFloat(), but then number formatting is lost. Instead, I suggest using a number formatting library like Numeral.js. To convert "4,250,000.40" to a numeral you'd use:
const num = numeral("4,250,000.40");
you can reformat your number using the format() method like so:
const formatedNum = numeral("4,250,000.40").format('0,0.00');
console.log(formatedNum); // "4,250,000.40"
Here's a working example, including more cool formatting:
const num = numeral("4,250,000.40");
const formatedNum = num.format('0,0[.]00');
console.log(formatedNum); // "4,250,000.40"
// you can format number as money
console.log(num.format('$0,0[.]00')); // $4,250,000.40
// you can use abbreviations like k or m
console.log(num.format('$0.00a')); // $4.25m
// you can use financial notation
console.log(numeral("-4,250,000.40").format('($0,0)')); // ($4,250,000)
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>

how to evaluate this Number("2/4") in JavaScript [duplicate]

This question already has answers here:
Evaluating a string as a mathematical expression in JavaScript
(26 answers)
Closed 7 years ago.
Hey guys i want to extract/evaluate the answer 2/4 in a string even ehen doing Number ("2/4") it gives me NaN as a result which is fairly reasonable! So my question is how can i evaluate this fraction from a string?
You can do eval("2/4"), which will properly result in 0.5.
However, using eval is a really bad idea...
If you always have a fraction in format A/B, you can split it up and compute:
var s = "11/47";
var ssplit = s.split('/');
document.body.innerText = ssplit[0] / ssplit[1];
Note that Division operator / will implicitly cast strings "11" and "47" to 11 and 47 Numbers.
You are looking for eval. Note
parseFloat("2/4")
2
parseFloat("4/2")
4
eval("4/2")
2
eval("2/4")
0.5
function myFunction() {
var str = "3/4";
var res = str.split("/");
alert(parseFloat(res[0]/res[1]));
}
Try with eval function :
eval("2/4");
Parsing the string only valid for numbers like 0-10 and a decimal (.) and all other if included will then result in NaN.
So, what you can do is like this:
Number(2/4)//0.5
parseFloat(2/4)//0.5
Number('2')/Number('4');//0.5
parseFloat('2')/parseFloat('4');//0.5
Number('2/4');//NaN as / is not parsable string for number
parseFloat('2/4');//2 as upto valid parsable string
parseFloat('1234/4');//1234
So, you can split string then use that like #Yeldar Kurmangaliyev answered for you.
(function(str){
var numbers = str.split("/").map(Number);
return numbers[0] / numbers[1];
})("2/4")
Keep in mind this does not check for invalid input.

How to convert string separated by commas to array? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Convert JS object to JSON string
Store comma separate values into array
I have a string containing values separated with commas:
"1,4,5,11,58,96"
How could I turn it into an object? I need something like this
["1","4","5","11","58","96"]
This will convert it into an array (which is the JSON representation you specified):
var array = myString.split(',');
If you need the string version:
var string = JSON.stringify(array);
In JSON, numbers don't need double quotes, so you could just append [ and ] to either end of the string, resulting in the string "[1,4,5,11,58,96]" and you will have a JSON Array of numbers.
make it an array
var array = myString.split(',');

JQuery Filter Numbers Of A String [duplicate]

This question already has answers here:
Parsing an Int from a string in javascript
(3 answers)
Closed 9 years ago.
How do you filter only the numbers of a string?
Example Pseudo Code:
number = $("thumb32").filternumbers()
number = 32
You don't need jQuery for this - just plain old JavaScript regex replacement
var number = yourstring.replace(/[^0-9]/g, '')
This will get rid of anything that's not [0-9]
Edit: Here's a small function to extract all the numbers (as actual numbers) from an input string. It's not an exhaustive expression but will be a good start for anyone needing.
function getNumbers(inputString){
var regex=/\d+\.\d+|\.\d+|\d+/g,
results = [],
n;
while(n = regex.exec(inputString)) {
results.push(parseFloat(n[0]));
}
return results;
}
var data = "123.45,34 and 57. Maybe add a 45.824 with 0.32 and .56"
console.log(getNumbers(data));
// [123.45, 34, 57, 45.824, 0.32, 0.56];
Not really jQuery at all:
number = number.replace(/\D/g, '');
That regular expression, /\D/g, matches any non-digit. Thus the call to .replace() replaces all non-digits (all of them, thanks to "g") with the empty string.
edit — if you want an actual *number value, you can use parseInt() after removing the non-digits from the string:
var number = "number32"; // a string
number = number.replace(/\D/g, ''); // a string of only digits, or the empty string
number = parseInt(number, 10); // now it's a numeric value
If the original string may have no digits at all, you'll get the numeric non-value NaN from parseInt in that case, which may be as good as anything.

Categories