This question already has answers here:
Extract numbers from a string using javascript
(4 answers)
Closed 6 years ago.
I want to split the numbers out of a string and put them in an array using Regex.
For example, I have a string
23a43b3843c9293k234nm5g%>and using regex I need to get [23,43,3843,9293,234,5]
in an array
how can i achieve this?
Use String.prototype.match()
The match() method retrieves the matches when matching a string against a regular expression
Edit: As suggested by Tushar, Use Array.prototype.map and argument as Number to cast it as Number.
Try this:
var exp = /[0-9]+/g;
var input = "23a43b3843c9293k234nm5g%>";
var op = input.match(exp).map(Number);
console.log(op);
var text = "23a43b3843c9293k234nm5g%>";
var regex = /(\d+)/g;
alert(text.match(regex));
You get a match object with all of your numbers.
The script above correctly alerts 23,43,3843,9293,234,5.
see Fiddle http://jsfiddle.net/5WJ9v/307/
Related
This question already has answers here:
Parsing strings for ints both Positive and Negative, Javascript
(2 answers)
Closed 3 years ago.
I am trying to extract positive and negative integers from the given string. But able to extract only positive integers.
I am passing "34,-10" string into getNumbersFromString param
I am getting
Output:
['34','10']
The expected output should be
[34,-10]
How do I solve this problem?
function getNumbersFromString(numberString){
var regx = numberString.match(/\d+/g);
return regx;
}
console.log(getNumbersFromString("34,-10"));
You can also match the -sign(at least 0 and at most 1) before the number. Then you can use map() to convert them to number.
function getNumbersFromString(numberString){
var regx = numberString.match(/-?\d+/g).map(Number);
return regx;
}
console.log(getNumbersFromString("34,-10"));
Why use an regex here. What about split() and map()
function getNumbersFromString(numberString){
return numberString.split(',').map(Number)
}
console.log(getNumbersFromString("34,-10"));
Or is the input string not "clean" and contains also text?
You should use regex with conditional - symbol like that /-?\d+/, also you should convert string to number with e.g parseInt function.
RegEx:
This expression might help you to pass integers using a list of chars:
numbers 0-9
+
-
[+\-0-9]+
If you wish, you can wrap it with a capturing group, just to be simple for string replace using a $1:
([+\-0-9]+)
Graph:
This graph shows how the expression works:
Code:
function getNumbersFromString(numberString){
var regex = numberString.match(/[+\-0-9]+/g);
return regex;
}
console.log(getNumbersFromString("34, -10, +10, +34"));
Non regex version (assuming input strings are proper csv):
function getNumbersFromString(numberString){
return numberString.split(',').map(v => parseInt(v))
}
console.log(getNumbersFromString("34,-10"))
This question already has answers here:
Replace forward slash "/ " character in JavaScript string?
(9 answers)
Why this javascript regex doesn't work?
(1 answer)
Closed 4 years ago.
I have a string field 01/01/1986 and I am using replace method to replace all occurrence of / with -
var test= '01/01/1986';
test.replace('//g','-')
but it does't give desire result. Any pointer would be helpful.
You just have a couple issues: don't put the regex in quotes. That turns it into a string instead of a regex and looks for that literal string. Then use \/ to escape the /:
var test= '01/01/1986';
console.log(test.replace(/\//g,'-'))
A quick way is to use split and join.
var test= '01/01/1986';
var result = test.split('/').join('-');
console.log(result);
Note too that you need to save the result. The original string itself will never be modified.
This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 4 years ago.
I'm looking for some assistance with JavaScript/Regex when trying to format a string of text.
I have the following IDs:
00A1234/A12
0A1234/A12
A1234/A12
000A1234/A12
I'm looking for a way that I can trim all of these down to 1234/A12. In essence, it should find the first letter from the left, and remove it and any preceding numbers so the final format should be 0000/A00 or 0000/AA00.
Is there an efficient way this can be acheived by Javascript? I'm looking at Regex at the moment.
Instead of focussing on what you want to strip, look at what you want to get:
/\d{4}\/[A-Z]{1,2}\d{2}/
var str = 'fdfhfjkqhfjAZEA0123/A45GHJqffhdlh';
match = str.match(/\d{4}\/[A-Z]{1,2}\d{2}/);
if (match) console.log(match[0]);
You could seach for leading digits and a following letter.
var data = ['00A1234/A12', '0A1234/A12', 'A1234/A12', '000A1234/A12'],
regex = /^\d*[a-z]/gi;
data.forEach(s => console.log(s.replace(regex, '')));
Or you could use String#slice for the last 8 characters.
var data = ['00A1234/A12', '0A1234/A12', 'A1234/A12', '000A1234/A12'];
data.forEach(s => console.log(s.slice(-8)));
You could use this function. Using regex find the first letter, then make a substring starting after that index.
function getCode(s){
var firstChar = s.match('[a-zA-Z]');
return s.substr(s.indexOf(firstChar)+1)
}
getCode("00A1234/A12");
getCode("0A1234/A12");
getCode("A1234/A12");
getCode("000A1234/A12");
A regex such as this will capture all of your examples, with a numbered capture group for the bit you're interested in
[0-9]*[A-Z]([0-9]{4}/[A-Z]{1,2}[0-9]{2})
var input = ["00A1234/A12","0A1234/A12","A1234/A12","000A1234/A12"];
var re = new RegExp("[0-9]*[A-Z]([0-9]{4}/[A-Z]{1,2}[0-9]{2})");
input.forEach(function(x){
console.log(re.exec(x)[1])
});
This question already has answers here:
Parse query string in JavaScript [duplicate]
(11 answers)
Closed 8 years ago.
So let's say I have this HTML link.
<a id="avId" href="http://www.whatever.com/user=74853380">Link</a>
And I have this JavaScript
av = document.getElementById('avId').getAttribute('href')
Which returns:
"http://www.whatever.com/user=74853380"
How do I extract 74853380 specifically from the resulting string?
There are a couple ways you could do this.
1.) Using substr and indexOf to extract it
var str = "www.something.com/user=123123123";
str.substr(str.indexOf('=') + 1, str.length);
2.) Using regex
var str = var str = "www.something.com/user=123123123";
// You can make this more specific for your query string, hence the '=' and group
str.match(/=(\d+)/)[1];
You could also split on the = character and take the second value in the resulting array. Your best bet is probably regex since it is much more robust. Splitting on a character or using substr and indexOf is likely to fail if your query string becomes more complex. Regex can also capture multiple groups if you need it to.
You can use regular expression:
var exp = /\d+/;
var str = "http://www.whatever.com/user=74853380";
console.log(str.match(exp));
Explanation:
/\d+/ - means "one or more digits"
Another case when you need find more than one number
"http://www.whatever.com/user=74853380/question/123123123"
You can use g flag.
var exp = /\d+/g;
var str = "http://www.whatever.com/user=74853380/question/123123123";
console.log(str.match(exp));
You can play with regular expressions
Well, you could split() it for a one liner answer.
var x = parseInt(av.split("=")[1],10); //convert to int if needed
This question already has answers here:
How do I split a string, breaking at a particular character?
(17 answers)
Closed 3 years ago.
I want to split a comma separated string with JavaScript. How?
var partsOfStr = str.split(',');
split()
var array = string.split(',')
and good morning, too, since I have to type 30 chars ...
var result;
result = "1,2,3".split(",");
console.log(result);
More info on W3Schools describing the String Split function.
Use
YourCommaSeparatedString.split(',');