I have a two different different numbers, each with a dollar sign. I want to get the two numbers separately.
JavaScript:
function price_range(id){
//var str = $('#'+id).val();
var str = '$75 - $300';
var removeDollar = str.replace(/\$/,'');
alert(removeDollar);
}
Click Here
The above code only replaces the first dollar sign, but I have two dollar signs with number. How can I get 75 and 300 separately?
You can just get all the numbers from the string, like this
console.log('$75 - $300'.match(/(\d+)/g));
# [ '75', '300' ]
Note: This simple RegEx will match and get all the numbers, even if there are more than 2 numbers in the string. But for this simple task, you don't need a complicate RegEx.
If you want to fix your program, you can do it like this
console.log('$75 - $300'.replace(/\$/g, '').split(/\s*-\s*/));
# [ '75', '300' ]
replace(/\$/g, '') will replace $ symbol from the string and then you can split the string based on \s*-\s*, which means zero or more white space characters, followed by -, and followed by zero or more white space characters.
You could extend the regular expression in the .replace() function to have a global flag g:
str.replace(/\$/g,'');
The whole script would work like this, but will be specific to removing the $ sign.
function price_range(id){
//var str = $('#'+id).val();
var str = '$75 - $300';
var removeDollar = str.replace(/\$/g,'');
alert(removeDollar);
}
Click Here
An option would be to extract numbers with a regular expression like this:
var str = '$70 - $300 some other 500%';
var arrOfStrings = str.match(/\d+/gi);
// arrOfStrings = ['70', '300', '500']
var arrOfNrs = arrOfStrings.map(function (e) {
return parseInt(e);
}); // map not supported by all browsers. you can use the _.map from underscorejs.org
// arrOfNrs = [70, 300, 500]
Related
I'm working with a string where I need to extract the first n characters up to where numbers begin. What would be the best way to do this as sometimes the string starts with a number: 7EUSA8889er898 I would need to extract 7EUSA But other string examples would be SWFX74849948, I would need to extract SWFX from that string.
Not sure how to do this with regex my limited knowledge is blocking me at this point:
^(\w{4}) that just gets me the first four characters but I don't really have a stopping point as sometimes the string could be somelongstring292894830982 which would require me to get somelongstring
Using \w will match a word character which includes characters and digits and an underscore.
You could match an optional digit [0-9]? from the start of the string ^and then match 1+ times A-Za-z
^[0-9]?[A-Za-z]+
Regex demo
const regex = /^[0-9]?[A-Za-z]+/;
[
"7EUSA8889er898",
"somelongstring292894830982",
"SWFX74849948"
].forEach(s => console.log(s.match(regex)[0]));
Can use this regex code:
(^\d+?[a-zA-Z]+)|(^\d+|[a-zA-Z]+)
I try with exmaple and good worked:
1- somelongstring292894830982 -> somelongstring
2- 7sdfsdf5456 -> 7sdfsdf
3- 875werwer54556 -> 875werwer
If you want to create function where the RegExp is parametrized by n parameter, this would be
function getStr(str,n) {
var pattern = "\\d?\\w{0,"+n+"}";
var reg = new RegExp(pattern);
var result = reg.exec(str);
if(result[0]) return result[0].substr(0,n);
}
There are answers to this but here is another way to do it.
var string1 = '7EUSA8889er898';
var string2 = 'SWFX74849948';
var Extract = function (args) {
var C = args.split(''); // Split string in array
var NI = []; // Store indexes of all numbers
// Loop through list -> if char is a number add its index
C.map(function (I) { return /^\d+$/.test(I) === true ? NI.push(C.indexOf(I)) : ''; });
// Get the items between the first and second occurence of a number
return C.slice(NI[0] === 0 ? NI[0] + 1 : 0, NI[1]).join('');
};
console.log(Extract(string1));
console.log(Extract(string2));
Output
EUSA
SWFX7
Since it's hard to tell what you are trying to match, I'd go with a general regex
^\d?\D+(?=\d)
I am trying to find out a regular expression where I can validate the input and also extract required information from input.
My input contains a simple calculation like addition, subtraction, multiplication and division.
For example: if input is addtion say 7.01+9.05
var input = '7.01+9.05';
var pattern = /^-?\d+\.?\d+[-+*\/]-?\d+\.?\d+$/
var sign;
if (input.match(pattern)) {
var matches = pattern.exec(input);
var left = // logic to extract value 7.01 using matches variable;
var right = // logic to extract value 9.05 using matches variable;
var sing = // logic to extract symbol + using matches variable;
}
I have used the regular expression which I found from this post : Calculator Regular Expression with decimal point and minus sign
Can you please help me how to extract the required data in above code?
In your pattern ^-?\d+\.?\d+[-+*\/]-?\d+\.?\d+$ you want to match an optional dot using \d+\.?\d+ which works but now the minimum number of digits to match is 2 due to matching 2 times 1 or more digits using \d+ so 1+1 would not match.
What you could do if it are only simple calculations, you could use 3 capturing groups and match a digit with an optional decimal part using ?\d+(?:\.\d+)?
Your pattern might look like:
^(-?\d+(?:\.\d+)?)([-+*\/])(-?\d+(?:\.\d+)?)$
Explanation
^ Start of string
(-?\d+(?:\.\d+)?) Capture group 1, match 1+ digits with an optional decimal part
([-+*\/]) Capture group 2, match any of the listed in the character class
(-?\d+(?:\.\d+)?) Capture group 2, match 1+ digits with an optional decimal part
$ End of string
See the regex101 demo
For example
var regex = /^(-?\d+(?:\.\d+)?)([-+*\/])(-?\d+(?:\.\d+)?)$/;
[
"21+22",
"7.01+9.05",
"1-1",
"1*1",
"0*1000000",
"8/4"
].forEach(x => {
var res = x.match(regex);
var left = res[1];
var right = res[2];
var sing = res[3];
console.log(left, right, sing);
});
Sure!
You should define capture groups in your regex expression using () and |. It is important define a flag global to your regex to capture all groups.
There are 3 things you need to capture:
the left number -> ^-?\d+\.?\d+
the sign -> [-+*\/]
the right number -> -?\d+\.?\d+$
You should use | alternation to regex use the capturing groups like a or statement beetwen the groups.
The final regex will be:
var pattern = /(^-?\d+\.?\d+)|([-+*\/])|(-?\d+\.?\d+$)/g
The ouput result will be an array where the first position will be the left number, second position the sign and the third position a right number.
Therefore the rest of your code will looks like that:
if (input.match(pattern)) {
var matches = input.match(pattern); \\ I recommend use input.match here too
var left = matches[0];
var right = matches[2];
var sing = matches[1];
}
You can do that using split()
var input = '7.01+9.05';
var pattern = /^-?\d+\.?\d+[-+*\/]-?\d+\.?\d+$/
if (input.match(pattern)) {
var matches = pattern.exec(input)[0].split(/(\+|-|\*|\/)/);
var left = matches[0];
var right = matches[2];
var sign = matches[1];
console.log(left,sign,right);
}
I need to go through a textarea to find and separate certain strings, such as:
Example 1) Separate the numbers from the text.
String "KAEeqk41KK EeqkKEKQ3 EKEK 43" - Result: [41, 3, 43]
Example 2) Count the blanks in the String.
OBS: _ = blank space
String "KAkeaekaek _ kea41 __ 3k1k31"
You could separate the numbers using match() and count some match using length, I'm not sure what do you mean with blanks but this example could be useful.
//var str = document.getElementById("textarea").value;//<-- probably somethig like this
var str = "KAEeqk41KK EeqkKEKQ3 EKEK 43";
var str2 = "KAkeaekaek _ kea41 __ 3k1k31"
var numbers = str.match(/[0-9]+/g)
var blanks = str2.match(/_| /g).length//<-- count spaces and _
console.log(numbers)
console.log(blanks)
I have a string like this:
20 EQUALS 'Value goes here'
I want to split it up into 3 separate strings:
conditionField = 20
conditionOperation = 'EQUALS'
conditionValue = 'Value goes here'
I tried this to get the Condition Field:
var conditionField = condition.replace(/(.*)(.*EQUALS)/, '$1');
But it get's the beginning and the end.
I'm having trouble splitting it up and dealing with the white space and spaces in the value.
Your question would actually be a bit of challenge if you wanted to arbitrarily extract quoted terms along with individual words. But since you appear to have a rather fixed structure, starting with a single number, then a single word command, followed by a third term, we can use the following regex pattern here:
([^\\s]*)\\s+([^\\s]*)\\s+(.*)
Each term in parentheses above will be made available as a capture group after the match has been run. In this case, I just blanket everything after the first two terms together.
var string = "20 EQUALS 'Value goes here'";
var re = new RegExp("([^\\s]*)\\s+([^\\s]*)\\s+(.*)");
match = re.exec(string);
if (match != null) {
console.log(match[1])
console.log(match[2])
console.log(match[3])
}
Try this :
var data = '20 EQUALS 30';
var a = data.split(/(\d*) ([a-zA-Z]*) (\d*)/g);
conditionField = a[1];
conditionOperation = a[2];
conditionValue = a[3];
I am trying to make a HTML form that accepts a rating through an input field from the user. The rating is to be a number from 0-10, and I want it to allow up to two decimal places. I am trying to use regular expression, with the following
function isRatingGood()
{
var rating = document.getElementById("rating").value;
var ratingpattern = new RegExp("^[0-9](\.[0-9][0-9]?)?$");
if(ratingpattern.test(rating))
{
alert("Rating Successfully Inputted");
return true;
}
else
{
return rating === "10" || rating === "10.0" || rating === "10.00";
}
}
However, when I enter any 4 or 3 digit number into the field, it still works. It outputs the alert, so I know it is the regular expression that is failing. 5 digit numbers do not work. I used this previous answer as a basis, but it is not working properly for me.
My current understanding is that the beginning of the expression should be a digit, then optionally, a decimal place followed by 1 or 2 digits should be accepted.
You are using a string literal to created the regex. Inside a string literal, \ is the escape character. The string literal
"^[0-9](\.[0-9][0-9]?)?$"
produces the value (and regex):
^[0-9](.[0-9][0-9]?)?$
(you can verify that by entering the string literal in your browser's console)
\. is not valid escape sequence in a string literal, hence the backslash is ignored. Here is similar example:
> "foo\:bar"
"foo:bar"
So you can see above, the . is not escaped in the regex, hence it keeps its special meaning and matches any character. Either escape the backslash in the string literal to create a literal \:
> "^[0-9](\\.[0-9][0-9]?)?$"
"^[0-9](\.[0-9][0-9]?)?$"
or use a regex literal:
/^[0-9](\.[0-9][0-9]?)?$/
The regular expression you're using will parsed to
/^[0-9](.[0-9][0-9]?)?$/
Here . will match any character except newline.
To make it match the . literal, you need to add an extra \ for escaping the \.
var ratingpattern = new RegExp("^[0-9](\\.[0-9][0-9]?)?$");
Or, you can simply use
var ratingPattern = /^[0-9](\.[0-9][0-9]?)?$/;
You can also use \d instead of the class [0-9].
var ratingPattern = /^\d(\.\d{1,2})?$/;
Demo
var ratingpattern = new RegExp("^[0-9](\\.[0-9][0-9]?)?$");
function isRatingGood() {
var rating = document.getElementById("rating").value;
if (ratingpattern.test(rating)) {
alert("Rating Successfully Inputted");
return true;
} else {
return rating === "10" || rating === "10.0" || rating === "10.00";
}
}
<input type="text" id="rating" />
<button onclick="isRatingGood()">Check</button>
Below find a regex candidate for your task:
^[0-1]?\d(\.\d{0,2})?$
Demo with explanation
var list = ['03.003', '05.05', '9.01', '10', '10.05', '100', '1', '2.', '2.12'];
var regex = /^[0-1]?\d(\.\d{0,2})?$/;
for (var index in list) {
var str = list[index];
var match = regex.test(str);
console.log(str + ' : ' + match);
}
This should also do the job. You don't need to escape dots from inside the square brackets:
^((10|\d{1})|\d{1}[.]\d{1,2})$
Also if you want have max rating 10 use
10| ---- accept 10
\d{1})| ---- accept whole numbers from 0-9 replace \d with [1-9]{1} if don't want 0 in this
\d{1}[.]\d{1,2} ---- accept number with two or one numbers after the coma from 0 to 9
LIVE DEMO: https://regex101.com/r/hY5tG4/7
Any character except ^-]\ All characters except the listed special characters are literal characters that add themselves to the character class. [abc] matches a, b or c literal characters
Just answered this myself.
Need to add square brackets to the decimal point, so the regular expression looks like
var ratingpattern = new RegExp("^[0-9]([\.][0-9][0-9]?)?$");