I've an element like so
<span class='h310'>blah</span>
Now
console.log($(this).attr('class'));
renders
"h310"
but
console.log(parseInt($(this).attr('class')));
renders NaN instead of the very much needed 310.
What am I missing here and how to solve this?
UPDATE
The h is indeed static, I merely added it because "310" is not a valid class name according to the HTML spec while "h310" is.
The h is static
In that case you can simply replace the "h" and convert the string to a number using the unary plus:
+$(this).attr('class').replace('h', '');
> 310
JSFiddle demo.
You need to extract the number part of the string first. parseInt will only extract it automatically if there is no non-numeric character at the beginning of the string
var numberpart = $(this).attr('class').substring(1);
console.log(parseInt(numberpart, 10)); // make sure to provide the radix 10 for decimal numbers
parseInt method will not work here as the class contains the character "h".
Try this (with "h" is static)
<span id="sp1" class='h310'>blah</span>
$(document).ready(function(){
alert($('#sp1').attr('class'));
alert(parseInt($('#sp1').attr('class').replace('h', ''),10));
});
For a general solutions use regex.
console.log(parseInt($('#sp1').attr('class').match(/\d+/),10));
Live DEMO
Yes, obviously it returns NaN as parseInt method won't work for last number from string but if you have 310h then it could be parsed with parseInt:
So, use regular expression here:
console.log(parseInt($('span').attr('class').match(/\d+/),10));
working fiddle
As #James you can also use like this:
$(this).attr('class').replace(/[a-zA-Z ]/g, '');
Try this
var str= $('span').attr('class');
var thenum = str.replace( /^\D+/g, '');
console.log(thenum)
DEMO
Related
I have the following text "2345dsds34.000" and i want the following value '234534.00'. I plan to do this via regex replace but somehow it doesnt limit the decimal places to 2.
I am using this "2345dsds34.000".replace(/[^\d+(\.\d{1,2})$]/g, '') but it keeps giving me 234534.000. How can i force it to limit it to 2 decimal points.
console.log("2345dsds34.000".replace(/[^\d+(\.\d{1,2})$]/g, ''))
Thanks
You can use toFixed JS Number function
Number( "2345dsds34.000".replace(/[^\d+(\.\d{1,2})$]/g, '') ).toFixed(2)
You can simply slice the last digit off with .slice(0, -1):
console.log("2345dsds34.000".replace(/[^\d+(\.\d{1,2})$]/g, '').slice(0, -1));
That regex is targetting the characters between some digits and some other digits having a decimal place.
Snapshot from https://regex101.com/
Then, the .replace() method is removing them. That all it does.
Since you don't know how many extra decimal you may have... I suggest you to use parseFloat() and .tofixed(2).
Please have a look at those two documentation links. ;)
var value = parseFloat("2345dsds34.000".replace(/[^\d+(\.\d{1,2})$]/g, '')).toFixed(2);
console.log(value);
You can simply use
[^\d.]
let str = "2345dsds34.000"
let op = parseFloat(str.replace(/[^\d.]+/g, '')).toFixed(2)
console.log(op)
By using a Regex with capturing parentheses It will look like this
var regex = /(\d{4})[a-z]+(\d{2})\.(\d{2}).*/;
var input_chain = "2345dsds34.000";
var output = input_chain.replace(regex, "$1$2.$3");
console.log(output);
Each capturing parentheses can be references in the second part of the replace method by their position number prefixed with a $
How to convert 1,000 to 1000 using JavaScript.
console.log(parseInt(1,000));
is taking it as 1
You should replace the "," and then doo the parseInt
parseInt("1,000".replace(/,/g,""));
You need to replace comma with empty character. Something like this below:
parseInt("1,000".replace(/,/g, ""))
Try this,
var num = parseInt("1,000".replace(/\,/g, ''), 10);
As, we need to remove "comma" from the string.
We also need "10" as radix as the second parameter.
Thanks
You can use a regular expression to replace all non-digits except for - and . when passing the argument to parseInt:
function parseMyInt(str) {
return parseInt(str.replace(/[^-\.\d]/g,''));
}
console.log(parseMyInt("1,000"));
console.log(parseMyInt("1,000,000"));
console.log(parseMyInt("1,000.1234"));
console.log(parseMyInt("-1,000"));
Edit
Expanded the regex to account for negative numbers and decimals.
I have a string value of 41,123 and I want to convert it to an integer in JavaScript.
I tried parseInt(41,123, 10) and parseFloat, but nothing gives me correct answer.
ParseInt, parseFloat work well until comma is encountered, but to above the result is '41'.
Does anyone have an idea about the fix?
var myInt = parseInt("41,123,10".replace(/,/g,""));
Here is the solution:
Number(s.replace(/,/g, ""))
Regex is needed in replacement to remove all comma characters, otherwise only one comma will be replaced.
You can remove the comma, and then parse; let's say the number is variable s:
parseInt(s.replace(/,/g, '')
I just can't get this thing to work in javascript. So, I have a text "game_1" without the quotes and now i want to get that number out of it and I tried this:
var idText = "game_1";
re = /game_(.*?)/;
found = idText.match(re);
var ajdi = found[1];
alert( ajdi );
But it doesn't work - please point out where am I going wrong.
If you're only matching a number, you may want to try
/game_([0-9]+)/
as your regular expression. That will match at least one number, which seems to be what you need. You entered a regexp that allows for 0 characters (*) and let it select the shortest possible result (?), which may be a problem (and match you 0 characters), depending on the regex engine.
If this is the complete text, then there is no need for regular expressions:
var id = +str.split('_')[1];
or
var id = +str.replace('game_', '');
(unary + is to convert the string to a number)
If you insist on regular expression, you have to anchor the expression:
/^game_(.*?)$/
or make the * greedy by omitting the ?:
/game_(.*)/
Better is to make the expression more restrictive as #Naltharial suggested.
Simple string manipulation:
var idText = "game_1",
adji = parseInt(idText.substring(5), 10);
* means zero or more occurrences. It seems that combining it with a greediness controller ? results in zero match.
You could replace * with + (which means one or more occurrences), but as #Felix Kling notes, it would only match one digit.
Better to ditch the ? completely.
http://jsfiddle.net/G8Qt7/2/
Try "game_1".replace(/^(game_)/, '')
this will return the number
You can simply use this re /\d+/ to get any number inside your string
Consider a non-DOM scenario where you'd want to remove all non-numeric characters from a string using JavaScript/ECMAScript. Any characters that are in range 0 - 9 should be kept.
var myString = 'abc123.8<blah>';
//desired output is 1238
How would you achieve this in plain JavaScript? Please remember this is a non-DOM scenario, so jQuery and other solutions involving browser and keypress events aren't suitable.
Use the string's .replace method with a regex of \D, which is a shorthand character class that matches all non-digits:
myString = myString.replace(/\D/g,'');
If you need this to leave the dot for float numbers, use this
var s = "-12345.50 €".replace(/[^\d.-]/g, ''); // gives "-12345.50"
Use a regular expression, if your script implementation supports them. Something like:
myString.replace(/[^0-9]/g, '');
You can use a RegExp to replace all the non-digit characters:
var myString = 'abc123.8<blah>';
myString = myString.replace(/[^\d]/g, ''); // 1238
Something along the lines of:
yourString = yourString.replace ( /[^0-9]/g, '' );
Short function to remove all non-numeric characters but keep the decimal (and return the number):
parseNum = str => +str.replace(/[^.\d]/g, '');
let str = 'a1b2c.d3e';
console.log(parseNum(str));
In Angular / Ionic / VueJS -- I just came up with a simple method of:
stripNaN(txt: any) {
return txt.toString().replace(/[^a-zA-Z0-9]/g, "");
}
Usage on the view:
<a [href]="'tel:'+stripNaN(single.meta['phone'])" [innerHTML]="stripNaN(single.meta['phone'])"></a>
The problem with these answers above, is that it assumes whole numbers. But if you need a floating point value, then the previous reg string will remove the decimal point.
To correct this you need write a negated character class with ^
var mystring = mystring.replace(/[^0-9.]/g, '');
try
myString.match(/\d/g).join``
var myString = 'abc123.8<blah>'
console.log( myString.match(/\d/g).join`` );
Unfortunately none of the answers above worked for me.
I was looking to convert currency numbers from strings like $123,232,122.11 (1232332122.11) or USD 123,122.892 (123122.892) or any currency like ₹ 98,79,112.50 (9879112.5) to give me a number output including the decimal pointer.
Had to make my own regex which looks something like this:
str = str.match(/\d|\./g).join('');
This,
.match(/\d|\.|\-/g).join('');
Handles both , and . also -
Example:
"Balance -$100,00.50".match(/\d|\.|\-/g).join('');
Outputs
10000.50
we are in 2017 now you can also use ES2016
var a = 'abc123.8<blah>';
console.log([...a].filter( e => isFinite(e)).join(''));
or
console.log([...'abc123.8<blah>'].filter( e => isFinite(e)).join(''));
The result is
1238