I have read few answers online and here on stack overflow but I am not finding a solution.
I am trying to prevent user from copy-pasting invalid characters (anything other than a-z A-Z characters) into my input field. I dont want to do this on submit but on copy-paste event.
If I copy paste text that has all invalid characters (like '1234'), my if block will get executed (regex test fails) and that works fine.
However, it does not work if my copied text contains mix of valid or invalid characters (like '12abc' or 'abc12').
How do I prevent user from copy-pasting text with invalid characters into my input text?
I am calling my javascript function on input text element like this:
function validatePaste(e) {
var regex = /[a-z]/gi;
var copiedText = e.clipboardData.getData('text')
console.log(copiedText,regex.test(copiedText) )
if (!regex.test(copiedText)) {
e.preventDefault(); //this line executes only if copiedText has all invalid characters
return false;
}
}
<input type="text" onpaste="validatePaste(event)">
References:
Character classes ([...]), Anchors (^ and $), Repetition (+, *)
The / are just delimiters, it denotes the start and the end of the regex. One use of this is now you can use modifiers on it.
function validatePaste(e) {
var regex = /^[a-zA-Z]*$/;
var copiedText = e.clipboardData.getData('text')
if (!regex.test(copiedText)) {
e.preventDefault(); //this line executes only if copiedText has all invalid characters
return false;
}
}
<input type="text" onpaste="validatePaste(event)">
You only test there is one char there
Here is a better regex - also we do not need to assign it every time
const regex = /^[a-z]+$/gi; // gi makes A-Z irrelevant
function validatePaste(e) {
const copiedText = e.clipboardData.getData('text')
console.log(copiedText, regex.test(copiedText))
if (!regex.test(copiedText)) {
e.preventDefault(); //this line executes if copiedText has any invalid characters
return false;
}
}
<input type="text" onpaste="validatePaste(event)">
Want to turn some text email#address.com into some text email#address.com
Below is the regex I'm using in replace:
'some text email#address.com'.replace(/([a-zA-Z0-9_\.\-]+)#(([[0-9]{1,3}' + '\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.' + ')+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)/gi, '<a href='mailto:$1'>$1</a>');
The regex is not working properly, please help.
As suggested by #Toto, you can use this regex \S+#\S+ to include every possible (and non-possible) characters in the email excluding the space.
(\S+#\S+)
If you want to include only English characters a-z, numbers 0-9, dots ., underscores _, and dashes - . You can do it this way:
([\w\.\-]+#\w+\.\w+)
If you want to add to the previous one every possible character from any language à è ì ò ù, and at the same time, exclude special characters % ^ & *, you can use \pL as follows:
([\w\.\-\pL]+#\w+\.\w+)
Demo for the last Regex:
var Email = "some text email#address.com.";
Email = Email.replace(/([\w\.\-\pL]+#\w+\.\w+)/g, '<a href=mailto:$1>$1</a>');
document.write (Email);
You can use replacer function of replace() function:
var str = "some text email#address.com";
var regex = /\w+#\w+\.\w+/gi;
var replacedString = str.replace( regex, function(match){
return ''+match+'';
});
console.log( replacedString );
Old question, but I was doing something like this in my code and had to fix a bug where the email address is already wrapped in a mailto link. This was my simple solution to that problem:
var rx = /([mailto:\w.\-pL]+#\w+.[\w.\-pL]+)/gi
return str.replace(rx, function (match) {
return (match.indexOf('mailto') === 0) ? match : `${match}`
})
The regex optionally matches "mailto:" and the replacer function checks to see if it is in the match, and returns it unmodified if so.
Maybe this will help a fellow google-passer-by.
So I am really bad at regex stuff ... I googled for an hour now and the best answer I could find is this one.
But I still can't for the sake of me figure it out ...
What I need is the following:
I have a JS array I need to .filter(). This arrays contains for example:
[ 'Gurken halbiert 2kg', 'Karotten geschnitten 5kg', 'Gurken RW' ]
For example: All of the following inputs should match the first entry ("Gurken halbiert 2kg"):
"Gu ha"
"gur h"
"gu halbi"
The following inputs should not match it:
"ken halbi"
"urk ha"
"gur biert"
Why? because one or more letters at the beginning of any word are missing.
More example inputs and the entries they should match:
input: "Gur" -> matches 1st and 3rd entry
input: "Kar g 5" -> matches 2nd
input: "G r" -> matches 3rd
I really hope someone can help as I am totally lost in this RegEx chaos - I never really understood them or how to use them.
Since the input varies, you would need to dynamically generate the regular expression.
In the function below, you will notice that we are basically building a string and then creating the regular expression using new RegExp(string, 'i').
The expression starts with a caret, and then basically follows the pattern:
^[[nth input char(s)]]\w*\s+[[nth input char(s)]]\w*\s+[[nth input char(s)]]\w*
It's worth pointing out that \w* is added after each input string and \s+ is added if it's not the last input string (i.e., not the end).
function generateRegex (input) {
var string = '^', arr = input.trim().split(' ');
arr.forEach(function (chars, i) {
string += chars + '\\w*' + (arr.length - 1 > i ? '\\s+' : '');
});
return new RegExp(string, 'i');
}
Then you can use the .filter() method on your array and return the elements that match:
var array = ['Gurken halbiert 2kg', 'Karotten geschnitten 5kg', 'Gurken RW'];
var filteredArray = array.filter(function (value) {
return value.match(generateRegex('Gur Ha'));
});
Output:
'Gur Ha' would match: ["Gurken halbiert 2kg"]
'Gur' would match: ["Gurken halbiert 2kg", "Gurken RW"]
'Kar g 5' would match: ["Karotten geschnitten 5kg"]
'G r' would match: ["Gurken RW"]
Example:
function generateRegex (input) {
var string = '^', arr = input.trim().split(' ');
arr.forEach(function (chars, i) {
string += chars + '\\w*' + (arr.length - 1 > i ? '\\s+' : '');
});
return new RegExp(string, 'i');
}
var array = ['Gurken halbiert 2kg', 'Karotten geschnitten 5kg', 'Gurken RW'];
var filteredArray = array.filter(function (value) {
return value.match(generateRegex('Gur'));
});
document.body.textContent = JSON.stringify(filteredArray);
Here is an example of how to filter user input as specified.
Notes
Escaping of regular expression characters from user input pattern (always sanitise user input).
Explicitly not using "\w" in order to support characters like "é".
Supports white space characters other than <space> like <tab> which can be copied and pasted into user input fields causing the user to think it's broken.
function doSubmit() {
// Get the user input search pattern string
var userInput = document.getElementById("myinput").value,
// List of strings to search
testList = [
'Gurken halbiert 2kg',
'Karotten geschnitten 5kg',
'Gurken RW'
],
// Between our "words" we allow zero or more non-space characters "[^\s]*"
// (this eats any extra characters the user might not have specified in their search pattern)
// followed by one or more white-space characters "\s+"
// (eating that space between the "words")
// Note that we are escaping the "\" characters here.
// Note we also don't use "\w" as this doesn't allow for characters like "é".
regexBetween = '[^\\s]*\\s+',
// Match the start of the string "^"
// Optionally allow one or more "words" at the start
// (this eats a "word" followed by a space zero or more times).
// Using an empty string here would allow "o g" to match the 2nd item in our test array.
regexStart = '^(?:' + regexBetween + ')*',
// Clean whitespace at begining and end
regexString = userInput.trim()
// Escape any characters that might break a regular expression
// Taken from: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
// Split into array of "words"
.split(/\s+/)
// Combine the "words" building our regular expression string
.join(regexBetween),
// Create the regular expression from the string (non-case-sensitive 'i')
regexObject = new RegExp(regexStart + regexString, 'i'),
// Filter the input array testing for matches against the regular expression.
resultsList = testList.filter(function(item) {
return regexObject.test(item);
});
// Ouput the array into the results text area, one per line.
document.getElementById('output').value = resultsList.join('\n') + '\n===the end===';
}
<form id="myform" onsubmit="doSubmit(); return false;">
<input type="text" id="myinput" value="" />
<input type="submit" name="submit" />
</form>
<textarea id="output" rows="5" cols="30">
</textarea>
I need to put in a field the input of time in minutes so I create this regular expression in javascript:
var pattern = new RegExp('[1-9]+[0-9]*') //the 0 is not a correct value for input
var example = "44445/";
if (pattern.test(example)) {
}
My problem is that the program enters in the if also in the string there is the "/" value. How is it possible?Anyone can example me?
You missed the start and end anchors. If you don't use anchors, then the regular expression will only check if the string contains the numbers.
Using anchors will make sure that the string contain only the specified characters.
var regex = /^[1-9]+[0-9]*$/;
Your regex can also be written as
var regex = /^[1-9]\d*$/;
function testValue(value) {
return /^[1-9]\d*$/.test(value);
}
<input type="text" onblur="document.getElementById('i1').value = testValue(this.value)">
<input type="text" readonly id="i1">
I need to find a reg ex that only allows alphanumeric. So far, everyone I try only works if the string is alphanumeric, meaning contains both a letter and a number. I just want one what would allow either and not require both.
/^[a-z0-9]+$/i
^ Start of string
[a-z0-9] a or b or c or ... z or 0 or 1 or ... 9
+ one or more times (change to * to allow empty string)
$ end of string
/i case-insensitive
Update (supporting universal characters)
if you need to this regexp supports universal character you can find list of unicode characters here.
for example: /^([a-zA-Z0-9\u0600-\u06FF\u0660-\u0669\u06F0-\u06F9 _.-]+)$/
this will support persian.
If you wanted to return a replaced result, then this would work:
var a = 'Test123*** TEST';
var b = a.replace(/[^a-z0-9]/gi, '');
console.log(b);
This would return:
Test123TEST
Note that the gi is necessary because it means global (not just on the first match), and case-insensitive, which is why I have a-z instead of a-zA-Z. And the ^ inside the brackets means "anything not in these brackets".
WARNING: Alphanumeric is great if that's exactly what you want. But if you're using this in an international market on like a person's name or geographical area, then you need to account for unicode characters, which this won't do. For instance, if you have a name like "Âlvarö", it would make it "lvar".
Use the word character class. The following is equivalent to a ^[a-zA-Z0-9_]+$:
^\w+$
Explanation:
^ start of string
\w any word character (A-Z, a-z, 0-9, _).
$ end of string
Use /[^\w]|_/g if you don't want to match the underscore.
/^([a-zA-Z0-9 _-]+)$/
the above regex allows spaces in side a string and restrict special characters.It Only allows
a-z, A-Z, 0-9, Space, Underscore and dash.
^\s*([0-9a-zA-Z]*)\s*$
or, if you want a minimum of one character:
^\s*([0-9a-zA-Z]+)\s*$
Square brackets indicate a set of characters. ^ is start of input. $ is end of input (or newline, depending on your options). \s is whitespace.
The whitespace before and after is optional.
The parentheses are the grouping operator to allow you to extract the information you want.
EDIT: removed my erroneous use of the \w character set.
For multi-language support:
var filtered = 'Hello Привет 你好 123_456'.match(/[\p{L}\p{N}\s]/gu).join('')
console.log(filtered) // --> "Hello Привет 你好 123456"
This matches any letter, number, or space in most languages.
[...] -> Match with conditions
[ab] -> Match 'a' OR 'b'
\p{L} -> Match any letter in any language
\p{N} -> Match any number in any language
\s -> Match a space
/g -> Don't stop after first match
/u -> Support unicode pattern matching
Ref: https://javascript.info/regexp-unicode
This will work
^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$
It accept only alphanumeriuc characters alone:
test cases pased :
dGgs1s23 - valid
12fUgdf - valid,
121232 - invalid,
abchfe - invalid,
abd()* - invalid,
42232^5$ - invalid
or
You can also try this one. this expression satisfied at least one number and one character and no other special characters
^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$
in angular can test like:
$scope.str = '12fUgdf';
var pattern = new RegExp('^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$');
$scope.testResult = pattern.test($scope.str);
PLUNKER DEMO
Refered:Regular expression for alphanumeric in Angularjs
Instead of checking for a valid alphanumeric string, you can achieve this indirectly by checking the string for any invalid characters. Do so by checking for anything that matches the complement of the valid alphanumeric string.
/[^a-z\d]/i
Here is an example:
var alphanumeric = "someStringHere";
var myRegEx = /[^a-z\d]/i;
var isValid = !(myRegEx.test(alphanumeric));
Notice the logical not operator at isValid, since I'm testing whether the string is false, not whether it's valid.
I have string similar to Samsung Galaxy A10s 6.2-Inch (2GB,32GB ROM) Android 9.0, (13MP+2MP)+ 8MP Dual SIM 4000mAh 4G LTE Smartphone - Black (BF19)
Below is what i did:
string.replace(/[^a-zA-Z0-9 ,._-]/g, '').split(',').join('-').split(' ').join('-').toLowerCase()
Notice i allowed ,._- then use split() and join() to replace , to - and space to - respectively.
I ended up getting something like this:
samsung-galaxy-a10s-6.2-inch-2gb-32gb-rom-android-9.0-13mp-2mp-8mp-dual-sim-4000mah-4g-lte-smartphone-black-bf19-20 which is what i wanted.
There might be a better solution but this is what i found working fine for me.
Extend the string prototype to use throughout your project
String.prototype.alphaNumeric = function() {
return this.replace(/[^a-z0-9]/gi,'');
}
Usage:
"I don't know what to say?".alphaNumeric();
//Idontknowwhattosay
Even better than Gayan Dissanayake pointed out.
/^[-\w\s]+$/
Now ^[a-zA-Z0-9]+$ can be represented as ^\w+$
You may want to use \s instead of space. Note that \s takes care of whitespace and not only one space character.
Input these code to your SCRATCHPAD and see the action.
var str=String("Blah-Blah1_2,oo0.01&zz%kick").replace(/[^\w-]/ig, '');
JAVASCRIPT to accept only NUMBERS, ALPHABETS and SPECIAL CHARECTERS
document.getElementById("onlynumbers").onkeypress = function (e) {
onlyNumbers(e.key, e)
};
document.getElementById("onlyalpha").onkeypress = function (e) {
onlyAlpha(e.key, e)
};
document.getElementById("speclchar").onkeypress = function (e) {
speclChar(e.key, e)
};
function onlyNumbers(key, e) {
var letters = /^[0-9]/g; //g means global
if (!(key).match(letters)) e.preventDefault();
}
function onlyAlpha(key, e) {
var letters = /^[a-z]/gi; //i means ignorecase
if (!(key).match(letters)) e.preventDefault();
}
function speclChar(key, e) {
var letters = /^[0-9a-z]/gi;
if ((key).match(letters)) e.preventDefault();
}
<html>
<head></head>
<body>
Enter Only Numbers:
<input id="onlynumbers" type="text">
<br><br>
Enter Only Alphabets:
<input id="onlyalpha" type="text" >
<br><br>
Enter other than Alphabets and numbers like special characters:
<input id="speclchar" type="text" >
</body>
</html>
A little bit late, but this worked for me:
/[^a-z A-Z 0-9]+/g
a-z : anything from a to z.
A-Z : anything from A to Z (upper case).
0-9 : any number from 0 to 9.
It will allow anything inside square brackets, so let's say you want to allow any other character, for example, "/" and "#", the regex would be something like this:
/[^a-z A-Z 0-9 / #]+/g
This site will help you to test your regex before coding.
https://regex101.com/
Feel free to modify and add anything you want into the brackets.
Regards :)
It seems like many users have noticed this these regular expressions will almost certainly fail unless we are strictly working in English. But I think there is an easy way forward that would not be so limited.
make a copy of your string in all UPPERCASE
make a second copy in all lowercase
Any characters that match in those strings are definitely not alphabetic in nature.
let copy1 = originalString.toUpperCase();
let copy2 = originalString.toLowerCase();
for(let i=0; i<originalString.length; i++) {
let bIsAlphabetic = (copy1[i] != copy2[i]);
}
Optionally, you can also detect numerics by just looking for digits 0 to 9.
Try this... Replace you field ID with #name...
a-z(a to z),
A-Z(A to Z),
0-9(0 to 9)
jQuery(document).ready(function($){
$('#name').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z0-9\s]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
});
Save this constant
const letters = /^[a-zA-Z0-9]+$/
now, for checking part use .match()
const string = 'Hey there...' // get string from a keyup listner
let id = ''
// iterate through each letters
for (var i = 0; i < string.length; i++) {
if (string[i].match(letters) ) {
id += string[i]
} else {
// In case you want to replace with something else
id += '-'
}
}
return id
Alphanumeric with case sensitive:
if (/^[a-zA-Z0-9]+$/.test("SoS007")) {
alert("match")
}
Also if you were looking for just Alphabetical characters, you can use the following regular expression:
/[^a-zA-Z]/gi
Sample code in typescript:
let samplestring = "!#!&34!# Alphabet !!535!!! is safe"
let regex = new RegExp(/[^a-zA-Z]/gi);
let res = samplestring.replace(regex,'');
console.log(res);
Note: if you are curious about RegEx syntax, visit regexr and either use the cheat-sheet or play with regular expressions.
Edit: alphanumeric --> alphabetical
Only accept numbers and letters (No Space)
function onlyAlphanumeric(str){
str.value=str.value.replace(/\s/g, "");//No Space
str.value=str.value.replace(/[^a-zA-Z0-9 ]/g, "");
}
<div>Only accept numbers and letters </div>
<input type="text" onKeyUp="onlyAlphanumeric(this);" >
Here is the way to check:
/**
* If the string contains only letters and numbers both then return true, otherwise false.
* #param string
* #returns boolean
*/
export const isOnlyAlphaNumeric = (string: string) => {
return /^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$/.test(string);
}
Jquery to accept only NUMBERS, ALPHABETS and SPECIAL CHARECTERS
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Enter Only Numbers:
<input type="text" id="onlynumbers">
<br><br>
Enter Only Alphabets:
<input type="text" id="onlyalpha">
<br><br>
Enter other than Alphabets and numbers like special characters:
<input type="text" id="speclchar">
<script>
$('#onlynumbers').keypress(function(e) {
var letters=/^[0-9]/g; //g means global
if(!(e.key).match(letters)) e.preventDefault();
});
$('#onlyalpha').keypress(function(e) {
var letters=/^[a-z]/gi; //i means ignorecase
if(!(e.key).match(letters)) e.preventDefault();
});
$('#speclchar').keypress(function(e) {
var letters=/^[0-9a-z]/gi;
if((e.key).match(letters)) e.preventDefault();
});
</script>
</body>
</html>
**JQUERY to accept only NUMBERS , ALPHABETS and SPECIAL CHARACTERS **
<!DOCTYPE html>
$('#onlynumbers').keypress(function(e) {
var letters=/^[0-9]/g; //g means global
if(!(e.key).match(letters)) e.preventDefault();
});
$('#onlyalpha').keypress(function(e) {
var letters=/^[a-z]/gi; //i means ignorecase
if(!(e.key).match(letters)) e.preventDefault();
});
$('#speclchar').keypress(function(e) {
var letters=/^[0-9a-z]/gi;
if((e.key).match(letters)) e.preventDefault();
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
Enter Only Numbers:
Enter Only Alphabets:
Enter other than Alphabets and numbers like special characters:
</body>
</html>