Validating Currency on Javascript using a regex not working - javascript

I need a regular expression for currency type.
Requirements :
1. First char can be a '$'. It can appear either 0 or 1 times.
2. Then a digit can appear multiple times.
3. Then a decimal point can appear either 0 or 1 time.
4. After this, a digit can appear 0 or more times.
I have written the following regular expression :
\$?\d+\.?\d*
I need to test this on JS . This is how i test this on JS;
var str = "$cng";
var patt = new RegExp('[\$?\d+\.?\d*]');
var res = patt.test(str);
console.log(res);
The above string $cng is returning true. I am not able to get it. Am i missing anything here. Can anyone please help. Thanks in advance.

You must need to escape all the backslashes one more times when passing it to the RegExp constructor which has double quotes as delimiter.
And also i suggest you to remove the square brackets around your pattern.
So change your pattern like below,
var patt = new RegExp("^\\$?\\d+\\.?\\d*$");
OR
var patt = new RegExp("^\\$?\\d+(?:\\.\\d+)?$");
Example:
> var str = "$123.12";
undefined
> var patt = new RegExp("^\\$?\\d+(?:\\.\\d+)?$");
undefined
> patt.test(str);
true
> var patt = new RegExp("^\\$?\\d+(?:\\.\\d+)?$");
undefined
> patt.test('$123.12$');
false

Replace RegExp('[\$?\d+\.?\d*]') with RegExp(/\$?\d+\.?\d*/) and it will work as expected.
Working Code Snippet:
var str = "$100.10";
var patt = new RegExp(/^\$?\d+\.?\d*$/);
var res = patt.test(str);
console.log(res);
EDIT:
You can also simply do: var res = /^\$?\d+\.?\d*$/.test(str);

Your regular expression should also match the beginning and end of the string, otherwise it will only test if the string contains a currency:
^\$?\d+\.?\d*$
You added brackets around the regular expression when you implemented it in Javascript, which changes the meaning entirely. The pattern will find a match if any of the characters within the brackets exist in the string, and as there is a $ in the string the result was true.
Also, when you have a regular expression in a string, you have to escape the backslashes:
var patt = new RegExp('^\\$?\\d+\\.?\\d*$');
You can also use a regular expression literal to create the object:
var patt = /^\$?\d+\.?\d*$/;
You might want to change the requirements so that the decimal point only is allowed if there are digits after it, so that for example $1. is not a valid value:
^\$?\d+(\.\d+)?$

[\$?\d+\.?\d*]==>[] is a character class.
Your regex will just match 1 character out of the all defined inside the character class.
Use
^\\$?\\d+\\.?\\d*$
or
/^\$?\d+\.?\d*$/
to be very safe.

Related

Javascript replace on multiple Japanese character

I want to replace this
"】|"
character from string with this"】".
mystring is ="【権利確定月】|1月"
and desired output is
"【権利確定月】1月".
I have tried with array operation and also with this code:
mystring.replace(/】|/g, '】')
but not working.
I only want to this with sequence for"】|".
Because after that string will grow like this
example:
"【権利確定月】1月|other|other|【other】other|other|other".
I have tried many other solution provided on stack overflow but all regex contain single character I want for above sequence character.
You need to escape the | because it has a special meaning within regex. 】| equates to 】 or (an empty string) so the result is that it replaces 】 with itself and inserts 】 between all the other characters in the string.
var mystring ="【権利確定月】|1月"
var myModifiedString = mystring.replace(/】\|/g, '】');
console.log(myModifiedString);
You need to escape the logical OR operator as it is a metacharacter in RegEx.
var x = "【権利確定月】|1月".replace(/】\|/g, '】');
console.log(x);
You can define the strings that need to be replaced in separate variables. Following worked for me.
var x = "】|";
var y = "】";
var word = "【権利確定月】|1月";
word.replace(x, y)
You can split your string by 】| and join by 】. Or (as was answered before me) escape | in regex.
const string = '【権利確】|】|定月】|1月';
let splitAndJoin = string.split('】|').join('】');
let replaceRegex = string.replace(/】\|/g, '】');
console.log(splitAndJoin);
console.log(replaceRegex);

regex for serial number in javascript

var serialNumber = $('#SerialNumber').val();
var serialNumberPattern = new RegExp('^[\s\da-zA-z\-.]+$');
if (!serialNumberPattern.test(serialNumber)) {
}
Above is the code I am using to validate a serial number which has alphanumeric characters, dots (.), dashes (-), and slashes (/) in it but somehow it's not working. Where am I going wrong? Please help.
When you're passing regex to RegExp constructor which uses " as regex delimiter, you have to escape all the backslashes one more time. Or otherwise it would be treated as an escape sequence.
var serialNumberPattern = new RegExp("^[\\s\\da-zA-Z.-]+$");
alphanumeric,dot(.),Dash(-),Slash(/) in it.
var serialNumberPattern = new RegExp("^[\\da-zA-Z./-]+$");
Just use /^[\s\da-zA-Z\-.\/]+$/, it's simple and works just fine.
You should only use the RegExp constructor when parts of the expression use a variable. This is not true in your case and just adds additional confusion.
document.write(/^[\s\da-zA-Z\-.\/]+$/.test('23 43-89'))

Javascript: RegExp not working no matter what my expression is

Ok, I've been using RegExp a number of times but for some reason I cannot get it to work this time. I am trying to test for latitude (0 to +/- 90 degrees). No matter what expression I use, it always returns false. Here's my code:
var regexLatitude = new RegExp("^-?([1-8]?[0-9]\.{1}\d{1,6}$|90\.{1}0{1,6}$)");
var status = regexLatitude.test("89.5");
I also tried without quotes:
var status = regexLatitude.test(89.5);
Any idea?
Your \ characters are being parsed by the Javascript string literal.
You need to use a regex literal:
var regexLatitude = /^-?([1-8]?[0-9]\.{1}\d{1,6}$|90\.{1}0{1,6}$)/;

Regexp for floating number

I found this regexp for validating floats. But I cant see how 2-1 will accepted. The below evaluates to true. I can't use parseFloat because I need to be able to accept "," instead of "." also. I wrote re2, same result though.
var re1 = new RegExp("^[-+]?[0-9]*\.?[0-9]+$");
console.log(re1.test("2-1"));
var re2 = new RegExp("^([0-9]+)\.([0-9]+)$");
console.log(re2.test("2-1"));
If you generate the regex using the constructor function, you have to to escape the backslash, i.e. \ becomes \\:
var re1 = new RegExp("^[-+]?[0-9]*\\.?[0-9]+$");
Another option is to use the literal syntax which doesn't require escaping:
var re1 = /^[-+]?[0-9]*\.?[0-9]+$/
Sometimes when you create a regex string, you even have to escape the backslash; this can of course be done with a backslash, so the final regex looks something like "\\.*", etc.
Doing this, I was able to get the correct results, as seen here:
var re1 = new RegExp("^[-+]?[0-9]*\\.?[0-9]+$");
console.log(re1.test("2-1"));
var re2 = new RegExp("^([0-9]+)\\.([0-9]+)$");
console.log(re2.test("2-1"));
console.log(re1.test("2.1"));
console.log(re2.test("2.1"));​
What about replacing a comma (",") with a period (".") and then using parseFloat?

RegExp.test not working?

I am trying to validate year using Regex.test in javascript, but no able to figure out why its returning false.
var regEx = new RegExp("^(19|20)[\d]{2,2}$");
regEx.test(inputValue) returns false for input value 1981, 2007
Thanks
As you're creating a RegExp object using a string expression, you need to double the backslashes so they escape properly. Also [\d]{2,2} can be simplified to \d\d:
var regEx = new RegExp("^(19|20)\\d\\d$");
Or better yet use a regex literal to avoid doubling backslashes:
var regEx = /^(19|20)\d\d$/;
Found the REAL issue:
Change your declaration to remove quotes:
var regEx = new RegExp(/^(19|20)[\d]{2,2}$/);
Do you mean
var inputValue = "1981, 2007";
If so, this will fail because the pattern is not matched due to the start string (^) and end string ($) characters.
If you want to capture both years, remove these characters from your pattern and do a global match (with /g)
var regEx = new RegExp(/(?:19|20)\d{2}/g);
var inputValue = "1981, 2007";
var matches = inputValue.match(regEx);
matches will be an array containing all matches.
I've noticed, for reasons I can't explain, sometimes you have to have two \\ in front of the d.
so try [\\d] and see if that helps.

Categories