I have a regex which checks the inputText is in valid url format or not.
And working almost good:
checkUrlFormat() {
const pattern = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
if (pattern.test(this.inputText) || this.inputText == null) {
return false;
}
return true;
}
But i need to make that pattern shorter so I have written a regexp in https://www.debuggex.com/#cheatsheet as
(((http|https)(://))?((www).)?)[a-z0-9]+(.|[a-z0-9])+[a-z0-9]
but it is in javascript format and i could not find how to use that string with the code above. When i directly copy paste it, it is giving syntax error. How can i combine them.
checkUrlFormat() {
const pattern = /^(((http|https)(:\/\/))?((www).)?)[a-z0-9]+(.|[a-z0-9])+[a-z0-9]$/;
if (pattern.test(this.inputText) || this.inputText == null) {
return false;
}
return true;
}
Related
My java-script regex validation requires the following condition.
Accept only alphabet value
Do not accept only numeric value
Do not accept only special characters
Accept combination of alphanumeric and special character value
I wrote following code to achieve it
function validateAlphaNumChar(str) {
var filter = /^[ A-Za-z0-9_##./#&+-]*$/;
if (filter.test(str)) {
return true;
}
else {
return false;
}
}
and I also tried different regex but never achieved the desired result.
Please do help me with the proper regex for my validations.
Thank You
Since, It is necessary to have alphabets in your string, simply check for that
function validateAlphaNumChar(str) {
var filter = /^[ A-Za-z0-9_##./#&+-]*$/;
var filterAlphabets = /^[ A-Za-z]*$/;
if (filter.test(str)) {
if ( filterAlphabets.test(str)){
return true;
}
else{
return false; }
}
else {
return false;
}
}
This is assuming that a combination of numbers and special characters is not allowed
If i understood the question right it should be like this
Check if it contains only numbers
Check if it contains only special symbols
function validateAlphaNumChar(str) {
var filterABC = /^[A-Za-z]*$/;
var filterNUM = /^[0-9]*$/;
var filterSPEC = /^[_##./#&+-]*$/;
if (filterNUM.test(str)) {
return false;
} else if(filterSPEC.test(str)) {
return false;
} else {
return true;
}
}
document.getElementById("demo").innerHTML = validateAlphaNumChar("A#");
<p id="demo"></p>
I am trying to validate a string where the first character must be an 'x' and the remaining characters must be numerical. For example:
x1234 == true;
k1234 == false;
x12k4 == false;
1x123 == false;
Here is my code:
function isValidCode(code){
var firstLetter = code.substring(0,1);
var remainingCode = code.substring(1);
var validCode = false;
// Debugging
console.log(firstLetter);
console.log(remainingCode);
if(firstLetter == 'x'){
validCode = true;
}
if(isNumeric(Number(remainingCode))){
validCode = true;
}
}
I've debugged my isNumeric() function, so I'm 99.9% sure the issue isn't there, but here it is just in case:
function isNumeric(numberIn)
{
var returnValue = true;
if (isNaN(numberIn) || isNaN(parseInt(numberIn, 10)))
{
returnValue = false;
}
return returnValue;
}
I've tried several things such as reversing my logic where I start with the given condidtion being true and then checking if(!(firstLetter == 'x')) I've tried == and ===and I've tried casting the remaining portion of the code with Number() , +() and not casting it at all, but none of these seeem to do the trick. The console does log the proper first character and remaining characters in the code so I'm not sure what is wrong.
You can use a regular expression test:
function isValidCode(code) {
return /^[a-z]\d+$/.test(code);
}
I am making an assumption that a lower case letter is required, followed by at least one digit.
To match only only the letter 'x', use:
function isValidCode(code) {
return /^x\d+$/.test(code);
}
You can use RegExp /^x(?=\d+$)/ to match x at beginning of input followed by digits followed by end of input
var arr = ["x1234"
, "k1234"
, "x12k4"
, "1x123"];
var re = /^x(?=\d+$)/;
arr.forEach(function(str) {
console.log(`${str}: ${re.test(str)}`)
})
I'd like to make the following code case-insensitive. If I test it out with
isSuffix("Albatross", "Ross")
it returns false, but if I try
isSuffix("Albatross", "ross")
it returns true.
How do I make it case-insensitive?
function isSuffix(str, suffix) {
if (str.substring(str.length - suffix.length) == suffix) {
return true;
return false;
}
Change your code to this (which makes use of .toLowerCase()
function isSuffix(str, suffix) {
return (str.substring(str.length - suffix.length).toLowerCase() == suffix.toLowerCase());
}
You can do this with regular expressions:
function isSuffix(str, suffix) {
var regSuffix = new RegExp(suffix + '$', 'i');
if ( regSuffix.test(str) ) {
return true;
}
return false;
}
Just use the toLowerCase function.
function isSuffix(str, suffix) {
str = str.toLowerCase();
if (str.substring(str.length - suffix.length) == suffix.toLowerCase()) {
return true;
}
return false;
}
You can use String.toLowerCase()
function isSuffix(str, suffix) {
if (str.substring(str.length - suffix.length).toLowerCase() == suffix.toLowerCase())
return true;
return false;
}
alert(isSuffix("Albatross", "Ross"))
You could use a regular expression, too, but this is closer to your original code.
Unless you can use case insensitive regular expression match with "i" (when suffix is either just text or cost of escaping worth it) you have to convert strings to lower case first before searching. Depending on your operations per-converting one or both to lower case may give better performance if you need to perform a lot of searches.
Creating new string to simply check if suffix matches could also be wasteful. For ancient browsers you can use lastIndexOf after converting string to lower case with toLowerCase.
For more modern JavaScript code (current versions of browsers/NodeJS) use endsWith (the link also includes polyfill):
function isSuffix(str, suffix) {
return (str.toLowerCase().endsWith(suffix.toLowerCase());
}
I've got this JavaScript function:
function emailaddresscheck() {
var emailregex = new RegExp("[A-Z0-9._%+-]+#[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)");
var emailstring = $("#email-address").val();
if (emailregex.test(emailstring)) {
$("#email-address-check").fadeIn(100);
return true;
}
else if ($("#email-address").val().length <= 5) {
$("#email-address-check").fadeOut(100);
return false;
}
}
The if condition is firing if I have a simple string in the RegExp constructor but this more complex regex isn't working.
Where am I going wrong?
UPDATE:
This is the finished working code:
function emailaddresscheck() {
var emailregexp = new RegExp("^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\\.(?:[A-Za-z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$");
var emailstring = $("#email-address").val();
if (emailregexp.test(emailstring) === true) {
$("#email-address-check").fadeIn(100);
return true;
}
else if (emailregexp.test(emailstring) === false) {
$("#email-address-check").fadeOut(100);
return false;
}
}
When you create a regex with the RegExp constructor you need to double escape special characters since they are inside a string.
new RegExp("[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)");
-^-
Or just use a literal regex:
/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)/
How can I check a JavaScript string is in a RegExp format, then convert it to RegExp?
I found a way with RegExp, but the rule is too complex to make it right.
function str2Regex(str){
var rule = /\/(\\[^\x00-\x1f]|\[(\\[^\x00-\x1f]|[^\x00-\x1f\\\/])*\]|[^\x00-\x1f\\\/\[])+\/([gim]*)/;
var match = str.match(rule);
return match ? new RegExp(match[1],match[3]) : str;
}
Now I'm using /\/(.*)\/(?=[igm]*)([igm]*)/ which works.
The simplest way, and probably the most correct, is to use try/catch :
try {
r = new RegExp(str);
} catch(error) {
// no good
}
You get a SyntaxError when the string doesn't match a well formed regular expression.
If you want to test a string whose value is like a compiled regular expression (for example "/\b=\b/g", you can use such a function :
function checkCompiledRegex(str) {
if (str[0]!='/') return false;
var i = str.lastIndexOf('/');
if (i<=0) return false;
try {
new RegExp(str.slice(1, i), str.slice(i+1));
} catch(error) {
return false;
}
return true;
}