Javascript RegEx for matching positive and negative integers [duplicate] - javascript

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"))

Related

Looking to trim a string using javascript / regex [duplicate]

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])
});

Javascript Regex For only numbers and no white spaces [duplicate]

This question already has an answer here:
Why this javascript regex doesn't work?
(1 answer)
Closed 2 years ago.
I was very surprised that I didn't find this already on the internet.
is there's a regular expression that validates only digits in a string including those starting with 0 and not white spaces
here's the example I'm using
function ValidateNumber() {
var regExp = new RegExp("/^\d+$/");
var strNumber = "010099914934";
var isValid = regExp.test(strNumber);
return isValid;
}
but still the isValid value is set to false
You could use /^\d+$/.
That means:
^ string start
\d+ a digit, once or more times
$ string end
This way you force the match to only numbers from start to end of that string.
Example here: https://regex101.com/r/jP4sN1/1
jsFiddle here: https://jsfiddle.net/gvqzknwk/
Note:
If you are using the RegExp constructor you need to double escape the \ in the \d selector, so your string passed to the RegExp constructor must be "^\\d+$".
So your function could be:
function ValidateNumber(strNumber) {
var regExp = new RegExp("^\\d+$");
var isValid = regExp.test(strNumber); // or just: /^\d+$/.test(strNumber);
return isValid;
}

Spliting numbers out of a string contain characters and numbers [duplicate]

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/

Removing any character besides 0-9 + - / * and ^ [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I'm trying to further my understanding of regular expressions in JavaScript.
So I have a form that allows a user to provide any string of characters. I'd like to take that string and remove any character that isn't a number, parenthesis, +, -, *, /, or ^. I'm trying to write a negating regex to grab anything that isn't valid and remove it. So far the code concerning this issue looks like this:
var pattern = /[^-\+\(\)\*\/\^0-9]*/g;
function validate (form) {
var string = form.input.value;
string.replace(pattern, '');
alert(string);
};
This regex works as intended on http://www.infobyip.com/regularexpressioncalculator.php regex tester, but always alerts with the exact string I supply without making any changes in the calculator. Any advice or pointers would be greatly appreciated.
The replace method doesn't modify the string. It creates a new string with the result of the replacement and returns it. You need to assign the result of the replacement back to the variable:
string = string.replace(pattern, '');

In JavaScript / jQuery what is the best way to convert a number with a comma into an integer? [duplicate]

This question already has answers here:
How can I parse a string with a comma thousand separator to a number?
(17 answers)
Closed last year.
I want to convert the string "15,678" into a value 15678. Methods parseInt() and parseFloat() are both returning 15 for "15,678." Is there an easy way to do this?
The simplest option is to remove all commas: parseInt(str.replace(/,/g, ''), 10)
One way is to remove all the commas with:
strnum = strnum.replace(/\,/g, '');
and then pass that to parseInt:
var num = parseInt(strnum.replace(/\,/g, ''), 10);
But you need to be careful here. The use of commas as thousands separators is a cultural thing. In some areas, the number 1,234,567.89 would be written 1.234.567,89.
If you only have numbers and commas:
+str.replace(',', '')
The + casts the string str into a number if it can. To make this as clear as possible, wrap it with parens:
(+str.replace(',', ''))
therefore, if you use it in a statement it is more separate visually (+ +x looks very similar to ++x):
var num = (+str1.replace(',', '')) + (+str1.replace(',', ''));
Javascript code conventions (See "Confusing Pluses and Minuses", second section from the bottom):
http://javascript.crockford.com/code.html
You can do it like this:
var value = parseInt("15,678".replace(",", ""));
Use a regex to remove the commas before parsing, like this
parseInt(str.replace(/,/g,''), 10)
//or for decimals as well:
parseFloat(str.replace(/,/g,''))
You can test it here.

Categories