I need some help creating regexp. It's just I don't quite understand how to create a regexp. How do i create a validation for username with some rules like this
only Uppercase, lowercase, underscore(_) and dot(.) are allowed
start with an underscore(_)
I've already tried some regexp from mozilla developer site, but it doesn't seems right
var usernameRegex = new RegExp(/_+[A-Za-z]/);
var usernameRegexFound = usernameRegex.test(username.value);
if (!usernameRegexFound) {
msg = "Invalid Username";
}
I expect some username like so
_username = true
_username1 = false
.username = false
username = false
and also are there any sites for me to understand how to create regexp, because I got some more thing to do with it
function validuser(username) {
var msg = "valid";
var usernameRegex = new RegExp(/_+[A-Za-z]/);
var usernameRegexFound = usernameRegex.test(username);
if (!usernameRegexFound) {
msg = "Invalid Username";
}
return msg;
}
console.log(validuser("_username","Valid?"));
console.log(validuser("_username1","Invalid?"));
console.log(validuser(".username","Invalid?"));
console.log(validuser("username","Invalid?"));
When creating regex, you can help yourself using https://regex101.com/.
That said, here is your regex :
function test(username) {
const regex = new RegExp('^_{1}[A-Za-z\.]*$', 'i');
// Alternative version considering #thomas points
// const regex = new RegExp('^_[A-Za-z._]+$', 'i');
return regex.test(username);
}
console.log(test('test'));
console.log(test('_test'));
console.log(test('_te.s.t'));
console.log(test('_teST'));
console.log(test('Test_'));
console.log(test('^zdq^dz.'));
console.log(test('_teS/T'));
console.log(test('_9901A'));
Related
I would like to use a variable in RegExp in this function.
checkSocial(platform, link) {
let reg = new RegExp(/^(?:https?:\/\/)?(www\.facebook\.com\/)(?:\S+)/);
return reg.test(link);
}
Doing this:
let reg = new RegExp(`/^(?:https?:\/\/)?(www\.${platform}\.com\/)(?:\S+)/`);
or this:
let reg = new RegExp('^(?:https?:\/\/)?(www\.' + platform + '\.com\/)(?:\S+)');
didn't work. How can I add a variable?
You don't need the slashes when creating RegExp this way, it will add them automatically.
Also, note you would need extra escaping - I think the last \S token was not escaped properly?
This seems to be a more valid pattern:
let platform = 'facebook';
let reg1 = new RegExp(`^(?:https?:\/\/)?(www\.${platform}\.com\/)(?:\S+)`)
let reg2 = new RegExp(`^(?:https?:\/\/)?(www\.${platform}\.com\/)(?:\\S+)`)
console.log("1", reg1) // Outputs: /^(?:https?:\/\/)?(www.facebook.com\/)(?:S+)/
console.log("2", reg2) // Outputs: /^(?:https?:\/\/)?(www.facebook.com\/)(?:\S+)/
I want a pattern with letters and numbers only.
This is how I do it...
JavaScript file:
var pattern_checked = checkPattern();
function checkPattern(){
var elem = document.getElementById("name");
var pattern = elem.getAttribute("[a-zA-Z0-9_]");
var re = new RegExp(pattern);
if (re.test(elem.value)) {
return true;
} else {
return false;
}
}
But in both the cases, I'm getting false.
What is wrong in this code?
I believe you meant to do:
function checkPattern() {
var elem = document.getElementById("name");
// Allow A-Z, a-z, 0-9 and underscore. Min 1 char.
var re = /^[a-zA-Z0-9_]+$/;
return re.test(elem.value);
}
Example fiddle
Your problem should be at this line.
var pattern = elem.getAttribute("[a-zA-Z0-9_]");
Attribute should usually have a name with value. But from your example, it seems like the value is also name.
The HTML code should be something like below:-
<input type='text' id='name' pattern='[a-zA-Z0-9_]'>
Then to get the pattern
var pattern = elem.getAttribute("pattern");
I am getting regex string from json object (yes its dynamic and will be always be string) i want to test this with textbox value.
But even if i pass valid input text it does not pass regex condition
code :
var pattern = "/^[A-Za-z\s]+$/";
var str = "Some Name";
pattern = new RegExp(pattern);
if(pattern.test(str))
{
alert('valid');
}
else
{
alert('invalid');
}
Fiddle :- http://jsfiddle.net/wn9scv3m/
Two problems:
You need to escape the backslash.
You need to remove the forward slashes on the beginning and end of string.
Corrected code:
var pattern = "^[A-Za-z\\s]+$";
var str = "Some Name";
pattern = new RegExp(pattern);
if(pattern.test(str))
{
alert('valid');
}
else
{
alert('invalid');
}
http://jsfiddle.net/wn9scv3m/3/
Use regex-parser:
const parseRegex = require("regex-parser")
parseRegex("/^hi$/g")
// => /^hi$/g
This should work for you (jsfiddle: http://jsfiddle.net/wn9scv3m/9/):
var pattern = /^[(\w)|(\s)]+$/; // using / regex constructor...
var altPattern = "^[(\w)|(\s)]+$"; // using quotes and new RegEx() syntax...
var regex = new RegExp(altPattern);
var str = "Some Name";
if (str.match(pattern) != null && regex.test(str) != null) { // check using both methods
alert('valid');
}
else {
alert('invalid');
}
As far as I can see in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions you are combining two methods to declare RegExp. If you are using the string variant, then don't include the "/" character before and after the expression, example:
var pattern = "^[A-Za-z\s]+$";
pattern = new RegExp(pattern);
If you like the /regexp/ form better, then use it without quotes:
pattern = /^[A-Za-z\s]+$/;
this should work
var str1 = "SomeName"; //true
var str2 = "SomeName123"; //false
function MyRegex(val) {
var pattern = /^[A-Za-z\s]+$/;
var match = pattern.exec(val);
return match !== null && match[0] === val;
}
alert(MyRegex(str1));
alert(MyRegex(str2));
I am working on an exercism. I am stuck on the first test that asks to match a regex to a new robot's name.
Here is the test ( I am only working on the one that doesn't have the x in front of it ).
var Robot = require('./robot-name');
describe("Robot", function() {
it("has a name", function() {
var robot = new Robot();
expect(robot.name).toMatch(/\w{2}\d{3}/);
});
xit("name is the same each time", function() {
var robot = new Robot();
expect(robot.name).toEqual(robot.name);
});
xit("different robots have different names", function() {
var robotOne = new Robot();
var robotTwo = new Robot();
expect(robotOne.name).not.toEqual(robotTwo.name);
});
xit("is able to reset the name", function() {
var robot = new Robot();
var originalName = robot.name;
robot.reset();
var newName = robot.name;
expect(originalName).not.toEqual(newName);
});
});
Here is my guess that isn't working.
var Robot = function(){
this.name = {};
Robot.prototype.new = function(robotNumber){
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 5;
var newName = Math.random().toString(36).slice(-5);
newName = MyRe.exec("/\w{2}\d{3}/");
newName.push(robotNumber);
this.name(newName);
};
};
module.exports = Robot;
Error message is on line 6 and responds:
Expected { } to match /\w{2}\d{3}/.
If anyone can point me in a direction of great resources for using prototypes and regex in javascript, it would be really helpful. Thank you.
In Your regex /\w{2}\d{3}/
\w{2} indicates word characters (a-z, A-Z, 0-9, _) (2 times) and
\d{3} indicates digits (0-9) (3 times)
And \w{2}\d{3} can be represented as,
And a matching example is : ab123
MyRe should be your regex such as /\w{2}\d{3}/g and .exec() should take in your string. You haven't defined MyRe. You could just write something like /\w{2}\d{3}/.exec(newName) if you wanted to be concise.
After trying to read your code it makes absolutely no sense. I can't even begin to imagine what your goal is.
I am trying to validate a twitter url, so that at least it contains a username. I do not care if it exists or not, just that there is one.
I am using the below javascript regex
var re = new RegExp('((http://)|(www\.))twitter\.com/(\w+)');
alert(re.test('http://twitter.com/test_user'));
but it is not working.
The strange thing is that I created and tested the above regex at this URL
http://www.regular-expressions.info/javascriptexample.html
where it works just fine.
Any ideas?
Thanks
function isTwitterHandle(handle) {
if (handle.match(/^((?:http:\/\/)?|(?:https:\/\/)?)?(?:www\.)?twitter\.com\/(\w+)$/i) || handle.match(/^#?(\w+)$/)) return true;
return false;
}
You need to escape the backslashes in the escape sequences too:
var re = new RegExp('((http://)|(www\\.))twitter\\.com/(\\w+)');
And I would recommend this regular expression:
new RegExp('^(?:http://)?(?:www\\.)?twitter\\.com/(\\w+)$', 'i')
It's because of the way you're defining the regex by using a string literal. You need to escape the escape characters (double backslash):
'^(http://)?(www\.)?twitter\.com/(\\w+)'
In the above, I also changed the start so that it would match http://www.twitter.com/test_user.
Alternatively, use the RegExp literal syntax, though this means you have to escape /:
var re = /^http:\/\/)?(www\.)?twitter\.com\/(\w+)/;
-http://twitter.com/username (this is http)
-https://twitter.com/username (this is https)
-twitter.com/username (without http)
-#username( with #)
-username (without #)
var username = "#test";
var r1 = new RegExp('^((?:http://)?|(?:https://)?)?(?:www\\.)?twitter\\.com/(\\w+)$', 'i');
if (r1.test(username) == false) {
var r2 = new RegExp('^#?(\\w+)$', 'j');
if (r2.test(username) == true)
return true;
else
return false;
} else {
return true;
}