Javascript Regex - javascript

why does this code return false:
var text = "3b3xx";
if(text.match("/^\d?b\d+xx$/")) {
return true;
}
return false;
I can not see any problem with my regular expression.. I want to return true, if the string starts with any numbers, followed by "b", followed by any numers, followed by "xx".

That's a string, not a regex.
Remove the "".

You are passing a string where a regular expression is expected.
var text = "3b3xx";
if(text.match(/^\d?b\d+xx$/)) {
return true;
}
return false;

Why not trying this:
var text = "3b3xx";
return text.match(/^\d?b\d+xx$/);

Just lose the quotes around your regex.
Regex is an object in Javascript, not a String.
/^\d?b\d+xx$/

Related

Palindrome Checker - can't get the function to check the phrase

My Palindrome checker function works for single strings i.e. 'dog' it works, but when it is a phrase i.e. 'nurses run' it does not work! here is my code:
function palindromeCheck(string) {
return string === string.split('').reverse().join('');
}
function palindromeCheck(string) {
string = string.replace(/\s+/g,'');
return string === string.split('').reverse().join('');
}
The s+ character means to match any number of whitespace characters (including tabs). The g character means to repeat the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.
Try this.
function palindromeCheck(string) {
string = string.replace(/\s/g, "");
return string === string.split('').reverse().join('');
}
console.log(palindromeCheck('nurses run'))

RegExp not matching results

I am trying to match a pattern in javascript.
Following is the example:
var pattern = "/^[a-z0-9]+$/i"; // This is should accept on alpha numeric characters.
var reg = new RegExp(pattern);
console.log("Should return false : "+reg.test("This $hould return false"));
console.log("Should return true : "+reg.test("Thisshouldreturntrue"));
When i run this I am getting both the results as false.
I do think that I am missing something simple. But little bit confused.
Thanks in advance.
You need not use slashes if you are using RegExp constructor. You either use enclosing slashes without double quotes to denote a regular expression or you pass a string (usually enclosed in quotes) to RegExp constructor:
var pattern = "^[a-z0-9]+$"; // This is should accept on alpha numeric characters.
var reg = new RegExp(pattern, "i");
console.log("Should return false : "+reg.test("This $hould return false"));
console.log("Should return true : "+reg.test("Thisshouldreturntrue"));
Your pattern is wrong. You don't need to use RegExp constructor here. And you need either ingnore case flag or add uppercase letters to range.
var reg = /^[a-zA-Z0-9]+$/;
console.log("Should return false : "+reg.test("This $hould return false"));
console.log("Should return true : "+reg.test("Thisshouldreturntrue"));

Remove Spaces and HTML Tags

Trying to make sure no one put a space in the username on sign up, I got the html tags to removed but not spaces.
Javascript:
$("#user").keypress(function (evt) {
if (isValid(String.fromCharCode(evt.which)))
return false;
});
function isValid(str) {
return /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
function stripspaces(input) {
input.value = input.value.replace(/\s/gi, "");
return true;
}
HTML:
Username: <input type="text" id="user"><br/>
You can see it here. http://jsfiddle.net/QshDd/63/
You can try with (each space character is being replaced, character by character, with the empty string):
str = str.replace(/\s/g, '');
or (each contiguous string of space characters is being replaced with the empty string by the "+" character):
str = str.replace(/\s+/g, '');
Ciao!
try this,
input.value.replace(/\n/g," ").replace( /<.*?>/g, "" );
You need to return the input value with the spaces removed:
function stripspaces(input)
{
return input.value.replace(/\s/gi,"");
}
The way you had it written the function just returned true regardless. Also, it seems you weren't calling the function (admittedly from only a quick read).
Although, it's probably easier to simply add \s (a regular expression special character for white-space characters) to the characters to replace, giving:
function isValid(str) {
return /[~`!#$%\^&*+=\-\[\]\\';,/\s{}|\\":<>\?]/g.test(str);
}
JS Fiddle demo.
References:
JavaScript regular expressions.

Convert string to RegExp

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;
}

Validating alphabetic only string in javascript

How can I quickly validate if a string is alphabetic only, e.g
var str = "!";
alert(isLetter(str)); // false
var str = "a";
alert(isLetter(str)); // true
Edit : I would like to add parenthesis i.e () to an exception, so
var str = "(";
or
var str = ")";
should also return true.
Regular expression to require at least one letter, or paren, and only allow letters and paren:
function isAlphaOrParen(str) {
return /^[a-zA-Z()]+$/.test(str);
}
Modify the regexp as needed:
/^[a-zA-Z()]*$/ - also returns true for an empty string
/^[a-zA-Z()]$/ - only returns true for single characters.
/^[a-zA-Z() ]+$/ - also allows spaces
Here you go:
function isLetter(s)
{
return s.match("^[a-zA-Z\(\)]+$");
}
If memory serves this should work in javascript:
function containsOnlyLettersOrParenthesis(str)
(
return str.match(/^([a-z\(\)]+)$/i);
)
You could use Regular Expressions...
functions isLetter(str) {
return str.match("^[a-zA-Z()]+$");
}
Oops... my bad... this is wrong... it should be
functions isLetter(str) {
return "^[a-zA-Z()]+$".test(str);
}
As the other answer says... sorry

Categories