Javascript regular expression match on string followed by number? - javascript

I have a string of the format: string:num where num is any number but string is a known string that I need to match on. I'd like to have this in an if statement as:
if( it matches 'string:' followed by a number) {
//do something
}

You want ...
if (stringYouHave.match(/^string:([0-9]+)$/)) {
// do something
}
This includes:
^ beginning of the string
string: the literal "string:" you mentioned
(.....) This subexpression, which you can refer to later if you need to know which number is in the string (though in this particular case, you could also just replace 'string:' with '')
[0-9] a character between 0 and 9 (i.e., a digit)
+ Must have at least one "of those" (i.e., digits mentioned above), but can have any number
$ end of the string

if( it.match(/^string:\d+$/) ( {
...
}

If you want only to check if the input string matches the pattern, you can use the RegExp.test function:
if (/^string:[0-9]+$/.test(input)){
//..
}
or with the String.search function:
if (input.search(/^string:[0-9]+$/) != -1){
//..
}
If you want to validate and get the number:
var match = input.match(/^string:([0-9]+)$/),
number;
if (match){
number = +match[1]; // unary plus to convert to number
// work with it
}

The above is good for integer numbers; if you want floating point numbers, or even scientific notation (as understood in C-like languages), you'll want something like this:
if (stringYouHave.match(/^string:[+-]?[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?$/))
{
// do something
}
You can remove the first [+-]? if you don't care about sign, the (.[0-9]+)? if you don't care about floating points, and the ([eE][+-]?[0-9]+)? if you don't care about scientific notation exponents. But if there's a chance you DO want to match those, you want to include them as optional in the regex.

if(teststring.match(new RegExp("^" + knownstring + ":\d+$"))) {
// some code
}

if(!!"string:5456".match(/^string:\d+$/)) { ... }
Number is a integer in the example above.

Related

check whether csv form or not [duplicate]

What is the regular expression to validate a comma delimited list like this one:
12365, 45236, 458, 1, 99996332, ......
I suggest you to do in the following way:
(\d+)(,\s*\d+)*
which would work for a list containing 1 or more elements.
This regex extracts an element from a comma separated list, regardless of contents:
(.+?)(?:,|$)
If you just replace the comma with something else, it should work for any delimiter.
It depends a bit on your exact requirements. I'm assuming: all numbers, any length, numbers cannot have leading zeros nor contain commas or decimal points. individual numbers always separated by a comma then a space, and the last number does NOT have a comma and space after it. Any of these being wrong would simplify the solution.
([1-9][0-9]*,[ ])*[1-9][0-9]*
Here's how I built that mentally:
[0-9] any digit.
[1-9][0-9]* leading non-zero digit followed by any number of digits
[1-9][0-9]*, as above, followed by a comma
[1-9][0-9]*[ ] as above, followed by a space
([1-9][0-9]*[ ])* as above, repeated 0 or more times
([1-9][0-9]*[ ])*[1-9][0-9]* as above, with a final number that doesn't have a comma.
Match duplicate comma-delimited items:
(?<=,|^)([^,]*)(,\1)+(?=,|$)
Reference.
This regex can be used to split the values of a comma delimitted list. List elements may be quoted, unquoted or empty. Commas inside a pair of quotation marks are not matched.
,(?!(?<=(?:^|,)\s*"(?:[^"]|""|\\")*,)(?:[^"]|""|\\")*"\s*(?:,|$))
Reference.
/^\d+(?:, ?\d+)*$/
i used this for a list of items that had to be alphanumeric without underscores at the front of each item.
^(([0-9a-zA-Z][0-9a-zA-Z_]*)([,][0-9a-zA-Z][0-9a-zA-Z_]*)*)$
You might want to specify language just to be safe, but
(\d+, ?)+(\d+)?
ought to work
I had a slightly different requirement, to parse an encoded dictionary/hashtable with escaped commas, like this:
"1=This is something, 2=This is something,,with an escaped comma, 3=This is something else"
I think this is an elegant solution, with a trick that avoids a lot of regex complexity:
if (string.IsNullOrEmpty(encodedValues))
{
return null;
}
else
{
var retVal = new Dictionary<int, string>();
var reFields = new Regex(#"([0-9]+)\=(([A-Za-z0-9\s]|(,,))+),");
foreach (Match match in reFields.Matches(encodedValues + ","))
{
var id = match.Groups[1].Value;
var value = match.Groups[2].Value;
retVal[int.Parse(id)] = value.Replace(",,", ",");
}
return retVal;
}
I think it can be adapted to the original question with an expression like #"([0-9]+),\s?" and parse on Groups[0].
I hope it's helpful to somebody and thanks for the tips on getting it close to there, especially Asaph!
In JavaScript, use split to help out, and catch any negative digits as well:
'-1,2,-3'.match(/(-?\d+)(,\s*-?\d+)*/)[0].split(',');
// ["-1", "2", "-3"]
// may need trimming if digits are space-separated
The following will match any comma delimited word/digit/space combination
(((.)*,)*)(.)*
Why don't you work with groups:
^(\d+(, )?)+$
If you had a more complicated regex, i.e: for valid urls rather than just numbers. You could do the following where you loop through each element and test each of them individually against your regex:
const validRelativeUrlRegex = /^(^$|(?!.*(\W\W))\/[a-zA-Z0-9\/-]+[^\W_]$)/;
const relativeUrls = "/url1,/url-2,url3";
const startsWithComma = relativeUrls.startsWith(",");
const endsWithComma = relativeUrls.endsWith(",");
const areAllURLsValid = relativeUrls
.split(",")
.every(url => validRelativeUrlRegex.test(url));
const isValid = areAllURLsValid && !endsWithComma && !startsWithComma

Formatting in Javascript

I have a question related to formatting strings.
User should parse a string in the Format XX:XX.
if the string parsed by user is in the format XX:XX i need to return true,
else false:
app.post('/test', (req, res) => {
if (req.body.time is in the format of XX:XX) {
return true
} else {
return false
}
});
You can use the RegExp.test function for this kind of thing.
Here is an example:
var condition = /^[a-zA-Z]{2}:[a-zA-Z]{2}$/.test("XX:XX");
console.log("Condition: ", condition);
The regex that I've used in this case check if the string is composed from two upper or lower case letters fallowed by a colon and other two such letters.
Based on your edits it seems that you're trying to check if a string represents an hour and minute value, if that is the case, a regex like this will be more appropriate /^\d{2}:\d{2}$/. This regex checks if the string is composed of 2 numbers fallowed by a colon and another 2 numbers.
The tool you're looking for is called Regular Expressions.
It is globally supported in almost every development platform, which makes it extremely convenient to use.
I would recommend this website for working out your regular expressions.
/^[a-zA-Z]{2}:[a-zA-Z]{2}&/g is an example of a Regular Expression that will take any pattern of:
[a-zA-Z]{2} - two characters from the sets a-z and A-Z.
Followed by :
Followed by the same first argument. Essentially, validating the pattern XX:XX. Of course, you can manipulate it as to what you want to allow for X.
^ marks the beginning of a string and $ marks the end of it, so ASD:AS would not work even though it contains the described pattern.
try using regex
var str = "12:aa";
var patt = new RegExp("^([a-zA-Z]|[0-9]){2}:([a-zA-Z]|[0-9]){2}$");
var res = patt.test(str);
if(res){ //if true
//do something
}
else{}

How to remove the first character from a string if it's a non-number in JavaScript?

I have a text field on a form that allows individuals to enter a price. I'm trying to allow other currency symbols to be entered into this field but my logic behind the scenes needs to strip out any currency symbols.
To make it easier, I really only care about the first character and only if it's a non number.
Otherwise, I can't use a solution that would remove any decimal points or commas in my price field or my calculations won't work.
Update: I'm currently using
itemCost = itemCost.replace(/\$/, '');
But now I'm trying to open it up to any currency sign.
You can access a string in the same way as you would an array. Take a look at the character at position zero of the string -
var inputString = '...' // whatever the user entered
var firstChar = inputString[0];
if (!Number.isInteger(firstChar)) {
inputString = inputString.substr(1)
}
I'm using the String.subStr function here to create a copy of the string starting from the 1st index.
Please take into consideration though that solution assumes that the provided string will only ever have one currency symbol. Inputs such as "USD $1.00" or even " $1.00" will not work with this solution.
An alternative would be to remove any character that is non numeric (excluding decimal points and commas) from the entire input string.
var inputString = '...' // whatever the user entered
var priceString = inputString.replace(/[^0-9\.,]/, '')
// $1.00 -> 1.00
// USD #$1,000.00 -> 1,000.00
Why don't you whitelist characters instead?
'$99,99'.match(/[0-9]+[,.]{0,1}[0-9]*/)
You'll certainly want to perfect it, I wrote it fast...
What the suggested regex does is make sure we have one or more digits, then maybe either a , or a . and 0 or more digits.
What I mostly want to point out with this answer is, while keeping just numeric characters is easy, it will by no mean make certain that the user entered a correct currency. The is also no way to know if the user entering 1,337 meant 1,337.00 or 1.337
There's a few ways you can do this... One way is to make the input into an array, check isNaN on the first element, and strip it if it's not a number.
const input = '$123.45';
const otherInput = '23.34';
function splitCheck(someInput) {
let arrayInput = someInput.split('');
if (isNaN(arrayInput[0])) {
arrayInput.shift();
return arrayInput.join('');
} else {
return someInput;
}
}
splitCheck(input); // returns 123.45
splitCheck(otherInput); // returns 23.34
Note you can also use a regexp, or you can also check for ASCII character values across an array, but this is just the first that came to mind.
A Javscript function could be
// Function to check first letter as numbers
function chkNumeric(inputtxt)
{
var letterNumber = '^[0-9]{1,}[ a-zA-Z0-9]*$';
if((inputtxt.value.match(letterNumber))
{
return true;
}
else
{
return false;
}
}
You may use parseInt()
parseInt() parses a string and returns an integer.
If the first character cannot be converted to a number, parseInt() returns NaN.
parseInt('Hello') // returns NaN
Also it's a good idea to trim() the string before using parseInt()
var money = '$123.45';
if( money ) { // check if variable is not null
money = money.trim();
}
console.log(parseInt(money));
// check NaN using isNaN function
if(isNaN(parseInt(money))) {
console.log('first charatcer is not a number')
money = money.substr(1);
console.log(money);
}
else {
console.log('first charatcer is a number')
}

print number with comma as hundred separator

I have a number like "7847258998" which I want to print with hundred comma separator in javascript.
The result should be:
7,84,72,58,998
i.e the first three digits from right should be grouped together. Remaining digits grouped in chunks of 2. I tried with following:
"7847258998".replace(/\B(?=(\d{3})+(\d{2})+(?!\d))/g, ",")
But it returns: 7,8,4,72,58998. What is the right expression?
Try this:
"7847258998".replace(/\B(?=(\d{2})*(\d{3})$)/g, ",");
I match the end of the string in the lookahead so that I'm always looking for something sane. Otherwise just about anything matches.
Tested on inputs length 1-10.. Enough to decide that it probably works. Pretty inefficient way to do it though, as for each character you have to parse the rest of the string.
But you did ask for a regular expression that does the job =)
function commafy(num)
{
num = num+"";
var re=/(-?\d+)(\d{3})/
while(re.test(num))
{
num=num.replace(re,"$1,$2")
}
return num;
}
function commafyback(num)
{
var x = num.split(',');
return parseFloat(x.join(""));
}
alert(commafy(7847258998))
You can convert the number to a locale string using the en-IN locale.
(7847258998).toLocaleString("en-IN")
If the value is a string, convert it to a number first:
const value = "7847258998"
Number(value).toLocaleString("en-IN")
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

How can I determine if a string only contains spaces, using javascript?

How can I determine if an input string only contains spaces, using javascript?
Another good post for : Faster JavaScript Trim
You just need to apply trim function and check the length of the string. If the length after trimming is 0 - then the string contains only spaces.
var str = "data abc";
if((jQuery.trim( str )).length==0)
alert("only spaces");
else
alert("contains other characters");
if (!input.match(/^\s*$/)) {
//your turn...
}
Alternatively, you can do a test() which returns a boolean instead of an array
//assuming input is the string to test
if(/^\s*$/.test(input)){
//has spaces
}
if(!input.match(/^([\s\t\r\n]*)$/)) {
blah.blah();
}
The fastest solution is using the regex prototype function test() and looking for any character that is not a space or a line break \S :
if (/\S/.test(str))
{
// found something other than a space or a line break
}
In case that you have a super long string, it can make a significant difference.

Categories

Resources