Allow comma after at least one number using regex - javascript

I need a regular expression allow comma after a number. i have tried But after number it allowing commas 122,,,
I want:
12,323,232,2,232
1,1,1,1,1
123123,23231,2322
I don;t want:
12312,,,123,,2,32,
12312,123,12,,,,,123,12
My code is
$(".experience").keyup(function (e) {
this.value = this.value.replace(/[^0-9\{0,9}]/g,'');
});

Is this what you're looking for? I'm not used to working with regex's, but managed to quickly put this together:
^([0-9]+\,?)*$
The questionmark is makes the comma optional.
[0-9] = numeric values only
+ = quantifier between 1 and unlimited
\ = escapes the character, so it's a constant
* = quantifier between 0 and unlimited times
Hope this helps!
Regards

If I understood your question correctly, you want to remove any commas not succeeding a number, and also remove any characters other than digits or commas. This is fairly simple if your language supported lookbehinds, however it isn't that hard in javascript too. You could use the below regex to match any incorrect commas and then replace them with $1
/^,+|(,)+|[^0-9,]+/g
Replace With: $1
Any commas at the start should be replaced with an empty string ''
Any commas which are consecutive i.e ,+, they should be replaced by a single comma i.e ,
Any characters other than digits or comma should be replaced with an empty string ''
To combine these two rules, ^,+|(,)+ will help match both and the replace $1 corresponds to capturing group 1, which will only be present in the 2nd condition so it will replace multiple commas with a single comma i.e (,)+ is replaced with (,). Whereas in the first alternative ^,+ which matches commas at the starting, there is the first capturing group remains empty so it gets replace with empty string ''
Here's a js demo:
$(function() {
$(".experience").keyup(function (e) {
this.value = this.value.replace(/^,+|(,)+|[^0-9,]+/g,'$1');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='experience' name="experience" value=""/>
You could consider changing keyup to focusout instead, although it's upto you! :)
Regex101 Demo

Related

Remove all the characters and special characters except underscores, dashes and numbers

Currently having a problem with removing all the alphabetic characters from string except '_', '-' and numbers.My string looks like follows.
let str = '/Anna-Charoline_1985-02-14_London/';
And i have tried following code to remove the unwanted characters.
let formatted = str.replace(/[D&\/\\#,+()$~%.'":*?<>{}]/g, '');
It did't work. Can anyone help me with this please? Expected output is _1985-02-14_.
This is way easier with a negated character class:
str.replace(/[^0-9_-]/g, '');
Everything that is not a digit between 0 and 9, an underscore or a minus, will get replaced by an empty string.
(The first - means “range” here, because it is between two other characters, the second one just means “itself”, because it is at the end of the character class. If it was placed somewhere other than the very start or end, it would need to be escaped, \-.)

Modify regex to disallow spaces

I'm working with the following regex:
var currentVal = $(this).val();
//making sure it's only numbers, decimals, and commas
var isValid = /^[0-9,.]*$/.test(currentVal);
and I'm trying to modify it so that it disallows spaces as well. I tried adding /s within the regex but it still allows it. Newer to regex, gets confusing quick
The brackets [] in your regex form a character class. ^ means start of string and $ means end of string with * applying the character class greedily multiple times. As it is written it should only allow characters specified in the class 0 through 9, comma, and period characters. If you tried adding in \s you would be also allowing for any whitespace characters in your character class, and thus cause your problem.
console.log(/^[0-9,.]*$/.test("123 903"));

Javascript: Regex removes the spaces?

I have this code that removes any Numeric values from an input field.
This works fine but the issue is that it will also remove the Spaces too which is not wanted.
This is my code:
$(document).on('keyup','.myclassname', function(e){
var regexp = /[^a-zA-Z]/g;
if($(this).val().match(regexp)){
$(this).val( $(this).val().replace(regexp,'') );
}
});
Can someone please advice on this?
your regex currently matches everything that is not english alphabet, if you only want to remove numeric content you can /[0-9]/g or /\d/g
var str = "1A3 AAA";
var regexp = /[0-9]/g;
console.log(str.replace(regexp, ""));
A quick answer would be to change this
var regexp = /[^a-zA-Z]g;
To this
[^a-zA-Z\s]
This means: Match a single character not present in the list below, characters from a-z, A-Z and \s (any whitespace character)
A shorter version, would be:
[0-9]+
This means: Match a single character PRESENT in the list below, Matching between one and unlimited times, only numbers from 0 to 9, achieving what you are really trying to do "remove any numeric values"
An even shorter version, would be:
[\d]+
Wich is equal to [0-9]+
Previously, you are excluding the characters you don't want, but is easier, shorter and faster if you select only the ones you want.

I need to regular expressions

I need two regular expression.
1) Any characters followed by a comma followed by any characters followed by a comma followed by any characters.
Currently I have:
/(.*,.*,.*)/
2) Any characters followed by a comma followed by any characters so long as they are not a comma.
Currently I have:
/(.*,.*[^,]+.*)/
Any help would be much appreciated. Thanks in advance!
For your first Regex you could really just use Javascript built in string.split(","); Which would return an array of strings. From there run a check for array.length >= 3 and you'll know the string matched you pattern. That being said f there are commas in the characters after that second required comma you could have issues depending on what you are expecting.
The second Regex could be verified using string.split(",") as well. Your second check would just be array.length === 2
The full code would be something like this
function verify(str) {
var arr = str.split(",");
if (arr.length < 2)
return "Invalid string provided";
if (arr.length === 2)
return arr[0] + arr[1];
return join(arr);
}
verify("some,crazy,comma delimited voodoo");
For your first regular expression, /(.*,.*,.*)/, you have what you're looking for. Note that "any character" includes commas, so really this only guarantees that there will be at least 2 commas.
For the second, /(.*,.*[^,]+.*)/, that's not quite right. "Any characters followed by a comma followed by any characters so long as they are not a comma" would be /(.*,[^,]*)/. However again, consider that "any characters" includes commas, so it is somewhat meaningless.
Perhaps you mean something more like /([^,]*,[^,]*)/? This is any text with precisely one comma. You can repeat the pattern by adding a second ,[^,]* as you wish, for example /([^,]*,[^,]*,[^,]*)/ is for precisely two commas.
If you wish to match any number of items separated by commas, try /([^,]+,?)/g to match each individual list item.
If you also require that there is text between commas, use + instead of *.
I don't know the utility of your regular expressions but in the linux grep command this will work:
grep '?,?,?'
grep '?,*[^,]'

How can I validate a minimum of 3 words in a HTML form?

I've been trying to solve this problem for some time, but I've been unable to. I have to make a form and I must validate the name input to have at least 3 words in it within JavaScript. I think the best way to do it is with Regex and its \b property.
This is
<input type="text" class="texto" name="Nombre" id="name" title="nombre_cliente" style="color:#888;" placeholder="Nombre del cliente" />
What I mean to do in my JavaScript code is this:
if(document.getElementById("name").value.match(RegExCodeForMin3Words) === null){
alert("Name invalid");
}
So far I've been unable to learn how to make regex match the amount of words (I'm still a beginner at Regex). Can you help me tackle this problem? Maybe Regex isn't the best option available to solve this?
Thanks!
Regex to match the string which contains atleast three words.
\S+\s+\S+\s+\S+
\S+ matches one or more non-space characters. If you mean word as any combination of non-space characters then you could use the above regex.
OR
\b\w+\b(?:.*?\b\w+\b){2}
DEMO
> /\b\w+\b(?:.*?\b\w+\b){2}/.test('foo bar buz')
true
> /\b\w+\b(?:.*?\b\w+\b){2}/.test('foo bar')
false
> /\b\w+\b(?:.*?\b\w+\b){2}/.test('foo bar bux foobar')
true
\w+ matches one or more word character. So this forms a single complete word. (?:.*?\b\w+\b){2} ensures that there must have another two words following the first word. {2} quantifier repeats the previous token exactly two times.
Don't use a regex to look for words, it's not necessary. Just split on whitespace.
var wordCount = document.getElementById("name").trim().split(/\s+/).length;
if( wordCount < 3 ) { ... }
Call trim() first so there is no leading or trailing whitespace that will get erroneously split. Then split it on \s+ which is the character group whitespace 1 or more times. split returns an array of all groups separated by the delimiter, which in this case is whitespace. The elements of the array will be all "words", or whatever is in the input separated by spaces.
Disclaimer: there is no 100% accurate method for tokenization (splitting words) in many languages.
You can't use \b because, unfortunately, it matches the "break" around most letters with diacritics (e.g. "é").
A simple approximation for romance languages is to look for spaces and apostrophes.
/.+?(?:[\s'].+?){2,}/
Explanation:
[\s'] matches a whitespace character or an apostrophe. It can be improved as much as you want (could include punctuation etc), but the idea is that it's "stuff between words". This part is what determines the quality of the tokenizer.
.+? matches any non-empty string that can't be matched by anything else. It doesn't say anything about what constitutes a word.
(?:[\s'].+?) is just a sequence of a delimiter and a "string between delimiters" (a word, we hope). The ?: in the beginning prevents the engine from capturing the group in parentheses, but it's not really necessary. We want the parentheses to apply a quantifier to the whole sequence.
The final regex, .+?(?:[\s'].+?){2,} means "a word, then 2 or more times the sequence of a delimiter + a word" (total 2+1=3 words minimum).
Furthermore, instead of using JavaScript, you can declaratively validate your text field with the pattern attribute:
<input type="text" name="Nombre" … required pattern=".+?(?:[\s'].+?){2,}">
I guess you can use the length method for this variable in javascript.
for example:
var s="123456";
you can just get the length by s.length

Categories