Javascript: Regex removes the spaces? - javascript

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.

Related

Regex replace not removing characters properly

I have the regular expression:
const regex = /^\d*\.?\d{0,2}$/
and its inverse (I believe) of
const inverse = /^(?!\d*\.?\d{0,2}$)/
The first regex is validating the string fits any positive number, allowing a decimal and two decimal digits (e.g. 150, 14., 7.4, 12.68). The second regex is the inverse of the first, and doing some testing I'm fairly confident it's giving the expected result, as it only validates when the string is anything but a number that may have a decimal and two digits after (e.g. 12..05, a5, 54.357).
My goal is to remove any characters from the string that do not fit the first regex. I thought I could do that this way:
let myString = '123M.45';
let fixed = myString.replace(inverse, '');
But this does not work as intended. To debug, I tried having the replace character changed to something I would be able to see:
let fixed = myString.replace(inverse, 'ZZZ');
When I do this, fixed becomes: ZZZ123M.45
Any help would be greatly appreciated.
I think I understand your logic here trying to find a regex that is the inverse of the regex that matches your valid string, in the hopes that it will allow you to remove any characters that make your string invalid and leave only the valid string. However, I don't think replace() will allow you to solve your problem in this way. From the MDN docs:
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.
In your inverse pattern you are using a negative lookahead. If we take a simple example of X(?!Y) we can think of this as "match X if not followed by Y". In your pattern your "X" is ^ and your "Y" is \d*\.?\d{0,2}$. From my understanding, the reason you are getting ZZZ123M.45 is that it is finding the first ^ (i.e, the start of the string) that is not followed by your pattern \d*\.?\d{0,2}$, and since 123M.45 doesn't match your "Y" pattern, your negative lookahead is satisfied and the beginning of your string is matched and "replaced" with ZZZ.
That (I think) is an explanation of what you are seeing.
I would propose an alternative solution to your problem that better fits with how I understand the .replace() method. Instead of your inverse pattern, try this one:
const invalidChars = /[^\d\.]|\.(?=\.)|(?<=\.\d\d)\d*/g
const myString = '123M..456444';
const fixed = myString.replace(invalidChars, '');
Here I am using a pattern that I think will match the individual characters that you want to remove. Let's break down what this one is doing:
[^\d\.]: match characters that are not digits
\.(?=\.): match . character if it is followed by another . character.
(?<=\.\d\d)\d*: match digits that are preceded by a decimal and 2 digits
Then I join all these with ORs (|) so it will match any one of the above patterns, and I use the g flag so that it will replace all the matches, not just the first one.
I am not sure if this will cover all your use cases, but I thought I would give it a shot. Here's a link to a breakdown that might be more helpful than mine, and you can use this tool to tweak the pattern if necessary.
I don't think you can do this
remove any characters from the string that do not fit the first regex
Because regex matching is meant for the entire string, and replace is used to replace just a PART inside that string. So the Regex inside replace must be a Regex to match unwanted characters only, not inverted Regex.
What you could do is to validate the string with your original regex, then if it's not valid, replace and validate again.
//if (notValid), replace unwanted character
// replace everything that's not a dot or digit
const replaceRegex = /[^\d.]/g; // notice g flag here to match every occurrence
const myString = '123M.45';
const fixed = myString.replace(replaceRegex, '');
console.log(fixed)
// validate again

Allow comma after at least one number using regex

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

RegEx to find all occurrences of a character not between two other characters

I'm looking for a regex (that I can implement in Javascript, so no lookbehinds) which will match all occurrences of a character, as long as it doesn't appear between two other characters. For example, I want to match all hyphens as long as they are not between plus signs.
----- // should match.
+---+ // should not match
---+---+--- // should only match the first 3 and last 3 characters.
I've tried adapting the method used in this post like so:
[-]+(?![^+]*\+)+
But it is not matching as desired. Any help is greatly appreciated.
P.S. Looking specifically for a REGEX solution. I realize this may not be the optimal solution but I'm specifically trying to improve my knowledge of regex.
If the delimiters (+ in your case) always come in pairs, you could use this:
var str = 'a-b-+-c-+-d-e'; // delimter is +
matches = str.match(/-(?=([^+]*\+[^+]*\+)*[^+]*$)/g, '');
console.log(matches); // 4 matches of `-`
This matches every hyphen that has an even number of pluses following it (could be zero).
Please try the following:
(?:^-+|-+$)
Regex101 demo: https://regex101.com/r/524iej/1
You can use use .replace to remove all text between 2 +s:
str = str.replace(/\+-*\+/g, '');
Example:
var str = '---+---+---';
str = str.replace(/\+-*\+/g, '');
//=> ------

javascript regex for special characters

I'm trying to create a validation for a password field which allows only the a-zA-Z0-9 characters and .!##$%^&*()_+-=
I can't seem to get the hang of it.
What's the difference when using regex = /a-zA-Z0-9/g and regex = /[a-zA-Z0-9]/ and which chars from .!##$%^&*()_+-= are needed to be escaped?
What I've tried up to now is:
var regex = /a-zA-Z0-9!##\$%\^\&*\)\(+=._-/g
but with no success
var regex = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]+$/g
Should work
Also may want to have a minimum length i.e. 6 characters
var regex = /^[a-zA-Z0-9!##\$%\^\&*\)\(+=._-]{6,}$/g
a sleaker way to match special chars:
/\W|_/g
\W Matches any character that is not a word character (alphanumeric & underscore).
Underscore is considered a special character so
add boolean to either match a special character or _
What's the difference?
/[a-zA-Z0-9]/ is a character class which matches one character that is inside the class. It consists of three ranges.
/a-zA-Z0-9/ does mean the literal sequence of those 9 characters.
Which chars from .!##$%^&*()_+-= are needed to be escaped?
Inside a character class, only the minus (if not at the end) and the circumflex (if at the beginning). Outside of a charclass, .$^*+() have a special meaning and need to be escaped to match literally.
allows only the a-zA-Z0-9 characters and .!##$%^&*()_+-=
Put them in a character class then, let them repeat and require to match the whole string with them by anchors:
var regex = /^[a-zA-Z0-9!##$%\^&*)(+=._-]*$/
You can be specific by testing for not valid characters. This will return true for anything not alphanumeric and space:
var specials = /[^A-Za-z 0-9]/g;
return specials.test(input.val());
Complete set of special characters:
/[\!\#\#\$\%\^\&\*\)\(\+\=\.\<\>\{\}\[\]\:\;\'\"\|\~\`\_\-]/g
To answer your question:
var regular_expression = /^[A-Za-z0-9\!\#\#\$\%\^\&\*\)\(+\=\._-]+$/g
How about this:-
var regularExpression = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{6,}$/;
It will allow a minimum of 6 characters including numbers, alphabets, and special characters
There are some issue with above written Regex.
This works perfectly.
^[a-zA-Z\d\-_.,\s]+$
Only allowed special characters are included here and can be extended after comma.
// Regex for special symbols
var regex_symbols= /[-!$%^&*()_+|~=`{}\[\]:\/;<>?,.##]/;
This regex works well for me to validate password:
/[ !"#$%&'()*+,-./:;<=>?#[\\\]^_`{|}~]/
This list of special characters (including white space and punctuation) was taken from here: https://www.owasp.org/index.php/Password_special_characters. It was changed a bit, cause backslash ('\') and closing bracket (']') had to be escaped for proper work of the regex. That's why two additional backslash characters were added.
Regex for minimum 8 char, one alpha, one numeric and one special char:
/^(?=.*[A-Za-z])(?=.*\d)(?=.*[!##$%^&*])[A-Za-z\d!##$%^&*]{8,}$/
this is the actual regex only match:
/[-!$%^&*()_+|~=`{}[:;<>?,.##\]]/g
You can use this to find and replace any special characters like in Worpress's slug
const regex = /[`~!##$%^&*()-_+{}[\]\\|,.//?;':"]/g
let slug = label.replace(regex, '')
function nameInput(limitField)
{
//LimitFile here is a text input and this function is passed to the text
onInput
var inputString = limitField.value;
// here we capture all illegal chars by adding a ^ inside the class,
// And overwrite them with "".
var newStr = inputString.replace(/[^a-zA-Z-\-\']/g, "");
limitField.value = newStr;
}
This function only allows alphabets, both lower case and upper case and - and ' characters. May help you build yours.
This works for me in React Native:
[~_!##$%^&*()\\[\\],.?":;{}|<>=+()-\\s\\/`\'\]
Here's my reference for the list of special characters:
https://owasp.org/www-community/password-special-characters
If we need to allow only number and symbols (- and .) then we can use the following pattern
const filterParams = {
allowedCharPattern: '\\d\\-\\.', // declaring regex pattern
numberParser: text => {
return text == null ? null : parseFloat(text)
}
}

jquery REGEX for longstring with azAZ-09-specialchars and |

Hello can someone help me in jquery regex?
whew coz im stack here since last night and finally iv'e decided to ask some help :)
any here's my regex abd the string is in exg variable.. then i want to split the string each
matches[0] = 'eNortjI0sLBScgQDz3yTfK98XCdH59RKc4M8&+SSXFzzXFz3UE9H9yzfYMfCYtPiDLes0NSAXCL3nIj0osJcIvNCjwxLv6z8YhPTXFxv8&KS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8WwMla1ww8SosXw==|eNortjI0NLRScgQDz3yTfK98XCdHr0pcJ+PAdP9sc+NcIvcyY4PEoNywyuyKzOQsC8twDx9Hg7TUkHyv7BDjMtPg3LwcjyinqlwiNxcXXCeXKFwn7wggEWmck59YHJhZ5Z4ZmF4R5eSfaFnkWuzpVFRglpxcXB7lEuWiZA1cMO+XJv4=|eNortjI0MLdScgQDz3yTfK98XCdHr7LgEpekEmO&xIBgo5CMoOSSKu&QDKPK5OziojS&&Bwvk&BK4yqLCFOjTNNcXC9Tz8C0jLzSkuCMYI88v8KIwORQi&TMQLM8i&B8Sy9Pl7QqXwt&gxQvrzLHKJcoFyVrXDCNviXB|eNortjI0NLRScgQDz3yTfK98XCdHn4pCp5yQxNIkM8MQ97SI0PLkoIqy9DJvZ3PXgPDwgKSIKKfwPKfi&CqvtAqTTNf0YMdwS8cM&yjH7Mr0omTTsLQqg&RcXLOK9Oz00LDgwijHCOeqyuC8KFwnf2fvSMcolygXJWtcMD&GXCfp|eNortjI0NLBScgQDz3yTfK98XCdHF6&gcEdTr5SiNO8KY1wnk1KLIE&&yowox+JcMB&XlGyzQH8&gwKvyIjyEMuyNI+ktMSQ7DDzdAsTA&fyKMckl&KS9HDDgNRKL0+jkCintLCStFwin+LcRC+PXFxcJ7+qwCiXKBcla1wwqjUmMg=='
if(regex.test(exg)) {
var matches = exg.match(regex);
for(var match in matches) {
alert(matches[match]);
}
} else {
alert("No matches found!");
}`
but my regex won't work whew can someone give me a right regex for it? :) please help..
Elias answer is probably the easiest way to do this but if you insist on regex then how about this:
var regex = /[a-zA-Z0-9\/-=&_+]+\|{0,1}/g
Explanation of your regex and why it doesn't work:
[a-zA-Z]+ // Match one or more a-z upper or lower case
[0-9]+ // *THEN* match one or more 0-9
[/-=&_]+ // *THEN* match one or more of these characters
| // *THEN* match a pipe
The problem here is that the letters, numbers and symbols in your search string are mixed together. Therefore they all need to go inside square brackets together so you match one or more of all of them together in any order. Yours puts them in a specific order, letters first, then numbers, then symbols.
The {0,1} on the end matches either zero or one pipe and will therefore catch the last match which does not have a pipe at the end.
Incidentely there's no such thing as JQuery regex. The regex functions are javascript.
erm... how about just using split like so marches = yourString.split('|');
this will return an array of strings, but the pipe char's will not be included, but just concat them to the substring if you need them.
You've missed a slash before |, so this may be what you want?
var regex = /[a-zA-Z0-9\/-=&_]+\|/g;

Categories