I have this regular expression to help me validate a form input.
var nrExp = /^\d{6}\-\d{4}$/;
This allows only 10 digits, where the last 4 digits are separated with a "minus sign".
012345-6789
I need to make it also allow it without the minus-sign AND with a space instead of a minus-sign:
0123456789
012345 6789
How can I remake this regexp to allow what I want?
Thanks
/^\d{6}[- ]?\d{4}$/
You don't need to escape the minus sign inside the brackets, as it does not give a range.
/^\d{6}[ \-]?\d{4}$/
var nrExp = /^\d{6}\[\- ]?\d{4}$/;
That should do it - either a blank space or a dash, made optional by the ?
var re = /^\d{6}[\- ]?\d{4}$/
console.log(re.test('012345-6789'));
console.log(re.test('012345 6789'));
console.log(re.test('0123456789'));
Sure. You just want to make the minus optional, along with a couple of other characters.
Try this one:
var nrExp = /^\d{6}(\-| )?\d{4}$/;
Notice the ? after the (\-| ). This allows that match portion to be optional.
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 $
I have variables that contain amounts and would like to remove the (US) thousand separators but also have to cover the scenario that there may be non-US formatted amounts where the comma is used for the decimals instead of for the thousands where I don't want to replace the comma.
Examples:
1,234,567.00 needs to become 1234567.00
1,234.00 needs to become 1234.00
but
1.234.567,00 needs to remain unchanged as not US format (i.e. comma here is used for decimals)
1.234,00 needs to remain unchanged as not US format (i.e. comma here is used for decimals)
I was thinking of using the following but wasn't sure about it as I am pretty new to Regex:
myVar.replace(/(\d+),(?=\d{3}(\D|$))/g, "$1");
What is best solution here? Note: I just need to cover normal amounts like the above examples, no special cases like letter / number combinations or things like 1,2,3 etc.
This one may suit your needs:
,(?=[\d,]*\.\d{2}\b)
Debuggex Demo
if (string.match(/\.\d{2}$/) {
string = string.replace(',', '');
}
or
string.replace(/,(?=.*\.\d+)/g, '');
Replace /,(?=\d*[\.,])/g with empty string?
http://regexr.com/39v2m
You can use replace() method to remove all the commas. They will be replaced with an empty string. I'm using reg exp with lookahead assertion to detect if a comma is followed by three digits, if so given comma will be removed.
string.replace(/,(?=\d{3})/g, '')
Examples:
'12,345,678.90'.replace(/,(?=\d{3})/g, '')
// '12345678.90'
'1,23,456.78'.replace(/,(?=\d{3})/g, '')
// '1,23456.78'
'$1,234.56'.replace(/,(?=\d{3})/g, '')
// '$1234.56'
This code is worked for me and you can use it in set amount val for remove separators
t.replace(/,(?=\d{3})/g, '')
myVar = myVar.replace(/([.,])(\d\d\d\D|\d\d\d$)/g,'$2');
Removes the period . or comma , when used as a thousand separator.
My objective is to replace all characters which are not dash (-) or not number or not letters in any language in a string.All of the #!()[], and all other signs to be replaced with empty string. All occurences of - should not be replaced also.
I have used for this the XRegExp plugin but it seems I cannot find the magic solution :)
I have tryed like this :
var txt = "Ad СТИНГ (ALI) - Englishmen In New York";
var regex = new XRegExp('\\p{^N}\\p{^L}',"g");
var b = XRegExp.replace(txt, regex, "")
but the result is : AСТИН(AL EnglishmeINeYork ... which is kind of weird
If I try to add also the condition for not removing the '-' character leads to make the RegEx invalid.
\\p{^N}\\p{^L} means a non-number followed by a non-letter.
Try [^\\p{N}\\p{L}-] that means a non-number, non-letter, non-dash.
A jsfiddle where to do some tests... The third XRegExp is the one you asked.
\p{^N}\p{^L}
is a non-number followed by a non-letter. You probably meant to say a character that is neither a letter nor a number:
[^\p{N}\p{L}]
// all non letters/numbers in a string => /[^a-zA-z0-9]/g
I dont know XRegExp.
but in js Regexp you can replace it by
b.replace(/[^a-zA-z0-9]/g,'')
This is my setup:
var test =
"http://tv.website.com/video/8086844/randomstring/".match(/^.+tv.website.com\/video\/(.*\d)/);
I want to extract the video id(8086844) and the regex does work, however when another digit is added after the "randomstring", it also matches the 8086844 + randomstring + other number.
What do I have to change in order to always get just the video id.
Try this regex
/^.+tv.website.com\/video\/([\d]+)/
It will search every digit character after ...video\ word and then give all the concordant digits thereafter till any non-digit character comes
The problem is the (.*\d) part, it looks for a greedy string ends with a digit, instead you need a continues series of digits after video/, it can be done via (\d+)
change it to
var test = "http://tv.website.com/video/8086844/randomstring/dd".match(/^.+tv.website.com\/video\/(\d+)/)[1];
var test = "http://tv.website.com/video/8086844/randomstring/8";
test = test.match(/^.+tv.website.com\/video\/(\d+)/);
console.log(test);
console.log(test[1]);
Output
[ 'http://tv.website.com/video/8086844',
'8086844',
index: 0,
input: 'http://tv.website.com/video/8086844/randomstring/8' ]
8086844
You are almost there. We know that, its going to be only numbers. So instead of .*\d we are gathering only the digits and grouping them using parens.
This is the simplest of all:
Use substr here
test.substr(28,7)
Fiddle
To extract out the id from your string test:We use substr(from,to)
Friends,
I'm new to both Javascript and Regular Expressions and hope you can help!
Within a Javascript function I need to check to see if a comma(,) appears 1 or more times. If it does then there should be one or more numbers either side of it.
e.g.
1,000.00 is ok
1,000,00 is ok
,000.00 is not ok
1,,000.00 is not ok
If these conditions are met I want the comma to be removed so 1,000.00 becomes 1000.00
What I have tried so is:
var x = '1,000.00';
var regex = new RegExp("[0-9]+,[0-9]+", "g");
var y = x.replace(regex,"");
alert(y);
When run the alert shows ".00" Which is not what I was expecting or want!
Thanks in advance for any help provided.
strong text
Edit
strong text
Thanks all for the input so far and the 3 answers given. Unfortunately I don't think I explained my question well enough.
What I am trying to achieve is:
If there is a comma in the text and there are one or more numbers either side of it then remove the comma but leave the rest of the string as is.
If there is a comma in the text and there is not at least one number either side of it then do nothing.
So using my examples from above:
1,000.00 becomes 1000.00
1,000,00 becomes 100000
,000.00 is left as ,000.00
1,,000.00 is left as 1,,000.00
Apologies for the confusion!
Your regex isn't going to be very flexible with higher orders than 1000 and it has a problem with inputs which don't have the comma. More problematically you're also matching and replacing the part of the data you're interested in!
Better to have a regex which matches the forms which are a problem and remove them.
The following matches (in order) commas at the beginning of the input, at the end of the input, preceded by a number of non digits, or followed by a number of non digits.
var y = x.replace(/^,|,$|[^0-9]+,|,[^0-9]+/g,'');
As an aside, all of this is much easier if you happen to be able to do lookbehind but almost every JS implementation doesn't.
Edit based on question update:
Ok, I won't attempt to understand why your rules are as they are, but the regex gets simpler to solve it:
var y = x.replace(/(\d),(\d)/g, '$1$2');
I would use something like the following:
^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)$
[0-9]{1,3}: 1 to 3 digits
(,[0-9]{3})*: [Optional] More digit triplets seperated by a comma
(\.[0-9]+): [Optional] Dot + more digits
If this regex matches, you know that your number is valid. Just replace all commas with the empty string afterwards.
It seems to me you have three error conditions
",1000"
"1000,"
"1,,000"
If any one of these is true then you should reject the field, If they are all false then you can strip the commas in the normal way and move on. This can be a simple alternation:
^,|,,|,$
I would just remove anything except digits and the decimal separator ([^0-9.]) and send the output through parseFloat():
var y = parseFloat(x.replace(/[^0-9.]+/g, ""));
// invalid cases:
// - standalone comma at the beginning of the string
// - comma next to another comma
// - standalone comma at the end of the string
var i,
inputs = ['1,000.00', '1,000,00', ',000.00', '1,,000.00'],
invalid_cases = /(^,)|(,,)|(,$)/;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].match(invalid_cases) === null) {
// wipe out everything but decimal and dot
inputs[i] = inputs[i].replace(/[^\d.]+/g, '');
}
}
console.log(inputs); // ["1000.00", "100000", ",000.00", "1,,000.00"]