javascript extract numbers from string not working - javascript

i have a sample str1 "14 girls"
str2 "178 guys"
i tried the following in chrome console to extract the numbers 12 and 178, could anyone please tell me what went wrong?
str.match(/^\d{2}$/) to get the number of girls i.e. `14`
str.match(/^[0-9]{2}?$/)
What would be an easy way to get the numbers?

If it's guaranteed that the numbers will always be at the start of the string, just use:
var n = parseInt(s, 10);
The parseInt() function will stop parsing at the first non-numeric character.
The reason your regular expressions didn't work is because you finished them with $ - meaning that they would only match if the entire string was a two digit number.

i think will be better:
str.match(/\d+(\.\d+)?/g)
This will give you an array of all numbers with float in it.

This is what I use:
var pattern=/[0-9]+/;
so...
var str='123abc';
//var str='abc123';
document.write(str.match(pattern));

Related

parseInt not working, get the number from the string

I'm trying to get the number from a string, please see my below snippet, I try "parseInt" but unfortunately not working, any help, ideas please?
var tt = "test 12";
console.log(parseInt(tt));
parseInt() won't work since tt is not beginning with a number.
You can use match() with RegEx to extract number from a string.
var num = tt.match(/\d+/)[0];

pos or neg two-numbers in string match using regex

Why is it that this regex almost works to return an array of two strings that can be used as numbers, positive or negative, but the 2nd string has its negative sign dropped? I can think of workarounds for this using another line or two of code, but would really like to get the regex to do it right. Thanks in advance. (By the way, the idea here is that the string can be "123,321" or "12.3, 321" or "123 32.1" or any reasonable formatting of two reals or integers.)
s="-123.23, -456.0";
s.match(/^([+-]?\d*\.\d*)\W+([+-]?\d*.\d*)$/);
//-->["-123.23, -456.0", "-123.23", "456.0"]
Instead of trying to match the entire line, you might consider just matching the numbers ...
var r = "-123.23, -456.0".match(/[+-]?\d+(?:\.\d+)?/g);
console.log(r); //=> [ '-123.23', '-456.0' ]
Try: [^\w-]+ instead \W+
s = "-123.23, -456.0";
s.match(/^([+-]?\d*\.\d*)[^\w-]+([+-]?\d*.\d*)$/)

How can I get the last part of a songkick URL using regex?

I need to get the last part after the slash from this URL or even just the number using regex:
http://www.songkick.com/artists/2884896-netsky
Does anyone know how I can go about doing this?
Many thanks,
Joe
I've got a regex pattern to find everything after the last slash - it is ([^//]+)$ . Thanks!
don't know if this is ok for you:
last part:
"http://www.songkick.com/artists/2884896-netsky".replace(/.*\//,"")
"2884896-netsky"
number:
"http://www.songkick.com/artists/2884896-netsky".replace(/.*\//,"").match(/\d+/)
["2884896"]
Try this:
var s = "http://www.songkick.com/artists/2884896-netsky";
s.match(/[^\/]+$/)[0]
[^\/]+ matches one or more characters other than /
$ matches the end of the string
For just the number, try:
var value = s.match(/(\d+)[^\/\d]+$/)[1];
value = parseInt(value, 10); // convert it to an Integer
(\d+) matches any Number and groups it
[^\/\d]+ matches anything besides Numbers or /
More Info on Javascript Regular Expressions

remove values from a string

Does anyone know how I would remove all leading zeros from a string.
var str = 000890
The string value changes all the time so I need it to be able to remove all 0s before a number greater than 0. So in the example above it needs to remove the first three 0s. So the result would be 890
It looks like we each have our own ways of doing this. I've created a test on jsperf.com, but the results are showing
String(Number('000890'));
is the quickest (on google chrome).
Here are the numbers for the updated test based on #BenLee's comment for Firefox, IE, and Chrome.
See: this question
var resultString = str.replace(/^[0]+/g,"");
var resultString = str.replace(/^[0]+/g,"");
I think a function like this should work
function replacezeros(text){
var newText = text.replace(/^[0]+/g,"");
return newText;
}
If it needs to stay as a string, cast it to a number, and cast it back to a string:
var num = '000123';
num = String(Number(num));
console.log(num);
You could also use the shorthand num = ''+(+num);. Although, I find the first form to be more readable.
parseInt('00890', 10); // returns 890
// or
Number('00890'); // returns 890
If your problem really is as you defined it, then go with one of the regex-based answers others have posted.
If the problem is just that you have a zero-padded integer in your string and need to manipulate the integer value without the zero-padding, you can just convert it to an integer like this:
parseInt("000890", 10) # => 890
Note that the result here is the integer 890 not the string "890". Also note that the radix 10 is required here because the string starts with a zero.
return str.replace(/^0+(.)/, '$1'));
That is: replace maximum number of leading zeros followed by any single character (which won't be a zero), with that single character. This is necessary so as not to swallow up a single "0"
you can simply do that removing the quotation marks.
var str = 000890;
//890
var str = "000890";
//000890

Numbers from string with javascript

candy 5.5, icecream 3.4, something valuable 1,185.5*2
Im using . and , for separators specifically.
im need to get from this string
var sum = 5.5 + 3.4 + 1185.5*2
My choice would be this:
var buildSumString = function(testString) {
rx=/(\d[\d\.\*]*)/g
return 'var sum = ' + testString.match(rx).join(' + ');
};
var testString = "candy 5.5, icecream 3.4, something valuable 1,185.5*2";
var rebuiltString = buildSumString(testString);
The only assumption to make here is that there will be no white space in your number strings, though that can be easily added.
I am quite sure this could be implemented using regular expressions
Using a pattern like
(?:([0-9.,*]+).*?)?
to find all occurrences (in java-script i think it is the g modifier) and then just some standard processing to remove all of the commas and then add the fields as usual
If you haven't used regular expressions before W3schools is usually a good place to start
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
Sorry i cant give anything more specific but i haven't used javascript enough
Poor design because you have a comma as a separator and also as a part of a number.
My advice is to make two passes through the string. First look for , between two digits followed by 3 digits, and delete the commas. Regular expresssions might be useful here. On the swecond pas split the string on the commas, then on each part scan from the right to the first space character to break off the numeric parts.
Build a string by adding plus signs, and then use eval to do the calculation. That will take care of any extra multiply operations.
You can get an expression string from your string like this[*]:
var str = 'candy 5.5, icecream 3.4, something valuable 1,185.5*2'
, sum = str.replace(/[a-z]+|,\s+/gi,'').trim().split(/\s+/).join(' + ');
and eval it. Still, you may want to think about other ideas to handle this (using a better separator in the initial string, a way to avoid eval (considered evil) etc.)
[*] trim being
String.prototype.trim = function(){
return this.replace(/^\s+|\s+$/,'');
}

Categories