Below is my code..
/(?!\*)/.test("test*test")
The result still return true.
I want to validate the string which will return false if any * in string.
Something is wrong with code?
Your regex returns true because it matches the starting position. The test you have just says "is there a position that is not followed by a *?" which literally any string will match - even "*" matches because after the * there is a position that is not followed by a(nother) *.
If you want to test if a string does not contain a *, the simplest solution is:
"test*test".indexOf("*") < 0 // true if no * in string
Doing so with regex would be something like:
/^[^*]*$/.test("test*test")
But that's more work.
Simply test for presence of * and negate the output
var string="123*456";
console.log( !(/\*/.test(string)) );
false
var string="12*34*56";
console.log( !(/\*/.test(string)) );
false
var string="123456";
console.log( !(/\*/.test(string)) );
true
Related
Why everything between / and / is going to print? It should give me error in console.
console.log normally print string enclosed within "" or any variable and object, in below case i am not passing string or any variable and object, but still it is printable.
var x = 10;
console.log(/m/);
console.log(/c/);
console.log(/&/);
console.log(/var/);
console.log(/x/);
Anything between / and / is considered to be regex. So, that's why it prints them out.
If you do a console.log( typeof /test/ ); it'll say Object which means that it is something.
JavaScript allows you to use the RegExp short hand like - /test/ which will match the string test in any given sequence.
Try something like:
let testOne = /test/;
let testTwo = new RegExp( 'test' );
console.log( testOne.test( 'test' ) );
console.log( testTwo.test( 'test' ) );
the code will output:
true
true
P.S.: The function regExp.test( String ) returns true if the String inside matches the expression defined in the regExp object.
I just need a really simple javascript regex test to make sure the last character of a given string is a number 0-9. I keep finding different variations of this in my searches but none that really match the simplicity of what I need. So for instance
var strOne = "blahblahblahblah"; // === false
var strTwo = "blahblahblahblah///"; // === false
var strThree = "blahblahblahblah123"; // === true
Any help is appreciated... I'm still trying to wrap my head around the rules of regex.
\d$ should do it.
\d - digit character class
$ - must match end of string
Tests:
/\d$/.test('blahblahblahblah'); // false
/\d$/.test('blahblahblahblah///'); // false
/\d$/.test('blahblahblahblah123'); // true
Try this regex /\d$/
var strOne = "blahblahblahblah";
var strTwo = "blahblahblahblah///";
var strThree = "blahblahblahblah123";
var regex = /\d$/;
console.log(regex.test(strOne)); // false
console.log(regex.test(strTwo)); // false
console.log(regex.test(strThree)); // true
This regex is pretty safe, give this a go: /\d+(\.\d+)?$/
I'm working on a simple password validator and wondering if its possible in Regex or... anything besides individually checking for each character.
Basically if the user types in something like "aaaaaaaaa1aaaaa", I want to let the user know that the character "1" is not allowed (This is a super simple example).
I'm trying to avoid something like
if(value.indexOf('#') {}
if(value.indexOf('#') {}
if(value.indexOf('\') {}
Maybe something like:
if(/[^A-Za-z0-9]/.exec(value) {}
Any help?
If you just want to check if the string is valid, you can use RegExp.test() - this is more efficient that exec() as it will return true when it finds the first occurrence:
var value = "abc$de%f";
// checks if value contains any invalid character
if(/[^A-Za-z0-9]/.test(value)) {
alert('invalid');
}
If you want to pick out which characters are invalid you need to use String.match():
var value = "abc$de%f";
var invalidChars = value.match(/[^A-Za-z0-9]/g);
alert('The following characters are invalid: ' + invalidChars.join(''));
Although a simple loop can do the job, here's another approach using a lesser known Array.prototype.some method. From MDN's description of some:
The some() method tests whether some element in the array passes the test implemented by the provided function.
The advantage over looping is that it'll stop going through the array as soon as the test is positive, avoiding breaks.
var invalidChars = ['#', '#', '\\'];
var input = "test#";
function contains(e) {
return input.indexOf(e) > -1;
}
console.log(invalidChars.some(contains)); // true
I'd suggest:
function isValid (val) {
// a simple regular expression to express that the string must be, from start (^)
// to end ($) a sequence of one or more letters, a-z ([a-z]+), of upper-, or lower-,
// case (i):
var valid = /^[a-z]+$/i;
// returning a Boolean (true/false) of whether the passed-string matches the
// regular expression:
return valid.test(val);
}
console.log(isValid ('abcdef') ); // true
console.log(isValid ('abc1def') ); // false
Otherwise, to show the characters that are found in the string and not allowed:
function isValid(val) {
// caching the valid characters ([a-z]), which can be present multiple times in
// the string (g), and upper or lower case (i):
var valid = /[a-z]/gi;
// if replacing the valid characters with zero-length strings reduces the string to
// a length of zero (the assessment is true), then no invalid characters could
// be present and we return true; otherwise, if the evaluation is false
// we replace the valid characters by zero-length strings, then split the string
// between characters (split('')) to form an array and return that array:
return val.replace(valid, '').length === 0 ? true : val.replace(valid, '').split('');
}
console.log(isValid('abcdef')); // true
console.log(isValid('abc1de#f')); // ["1", "#"]
References:
JavaScript conditional operator (assessment ? ifTrue : ifFalse).
JavaScript Regular Expressions.
String.prototype.replace().
String.prototype.split().
RegExp.prototype.test().
If I understand what you are asking you could do the following:
function getInvalidChars() {
var badChars = {
'#' : true,
'/' : true,
'<' : true,
'>' : true
}
var invalidChars = [];
for (var i=0,x = inputString.length; i < x; i++) {
if (badChars[inputString[i]]) invalidChars.push(inputString[i]);
}
return invalidChars;
}
var inputString = 'im/b#d:strin>';
var badCharactersInString = getInvalidChars(inputString);
if (badCharactersInString.length) {
document.write("bad characters in string: " + badCharactersInString.join(','));
}
I have a quick question.
How do I check whether there are any commas or dashes in a string? Thx
/[,\-]/.test(yourString)
this returns true if yourString contains commas or dashes or false otherwise.
/(,|-)/.test(yourString); // returns true if there are commas or dashes in the string, false otherwise.
You can use the indexOf() method to check the presence of a substring inside a string. If the return value is greater or equal to 0 there is at least one occurrence of the substring :
var str1 = "my-string";
var str2 = "string, mine";
var str3 "simple";
str1.indexOf("-"); //returns 2
str2.indexOf(","); //returns 6
str3.indexOf("-"); //returns -1
Use
var n = str.indexOf("some. text, here");
The indexOf() method returns the position of the first occurrence of a specified value in a string.
This method returns -1 if the value to search for never occurs.
Just checking index of , or -
Example code:
var str="dhfdshf-43sf";
if(str.indexOf('-')!=-1){
//- exist
}
var str2="dhfdshf,43sf";
if(str.indexOf(',')!=-1){
// , exist
}
I am building a very basic profanity filter that I only want to apply on some fields on my application (fullName, userDescription) on the serverside.
Does anyone have experience with a profanity filter in production? I only want it to:
'ass hello' <- match
'asster' <- NOT match
Below is my current code but it returns true and false on in succession for some reason.
var badWords = [ 'ass', 'whore', 'slut' ]
, check = new Regexp(badWords.join('|'), 'gi');
function filterString(string) {
return check.test(string);
}
filterString('ass'); // Returns true / false in succession.
How can I fix this "in succession" bug?
The test method sets the lastIndex property of the regex to the current matched position, so that further invocations will match further occurrences (if there were any).
check.lastIndex // 0 (init)
filterString('ass'); // true
check.lastIndex // 3
filterString('ass'); // false
check.lastIndex // now 0 again
So, you will need to reset it manually in your filterString function if you don't recreate the RegExp each time:
function filterString(string) {
check.lastIndex = 0;
return check.test(string);
}
Btw, to match only full words (like "ass", but not "asster"), you should wrap your matches in word boundaries like WTK suggested, i.e.
var check = new Regexp("\\b(?:"+badWords.join('|')+")\\b", 'gi');
You are matching via a substring comparison. Your Regex needs to be modified to match for whole words instead
How about with fixed regexp:
check = new Regexp('(^|\b)'+badWords.join('|')+'($|\b)', 'gi');
check.test('ass') // true
check.test('suckass') // false
check.test('mass of whore') // true
check.test('massive') // false
check.test('slut is massive') // true
I'm using \b match here to match for word boundry (and start or end of whole string).