I need following regexp such as..
the parenthesis are just to show the words
(abc) => pass
(abc ) => pass * abc with trailing white space
(abc ..blah..) => pass * ..blah.. means any chars containing spaces
(abcd) => fail
is there any good idea to do?
I trimmed the string so basically the first two cases are the same
but i couldn't make it fail when (abcd) comes in
if (/abc\b/im.test(subject)) {
// Successful match
} else {
// Match attempt failed
}
var doesItPass = (stringToValidate.split(" ")[0] == "abc") ? false : true;
Use regex:
/^abc\s*$/
Regex is the way of doing such things.
Related
Who can help me with the following
I create a rule with regex and I want remove all characters from the string if they not allowed.
I tried something by myself but I get not the result that I want
document.getElementById('item_price').onkeydown = function() {
var regex = /^(\d+[,]+\d{2})$/;
if (regex.test(this.value) == false ) {
this.value = this.value.replace(regex, "");
}
}
The characters that allowed are numbers and one komma.
Remove all letters, special characters and double kommas.
If the user types k12.40 the code must replace this string to 1240
Who can help me to the right direction?
This completely removes double occurrences of commas using regex, but keeps single ones.
// This should end up as 1,23243,09
let test = 'k1,23.2,,43d,0.9';
let replaced = test.replace(/([^(\d|,)]|,{2})/g, '')
console.log(replaced);
I don't believe there's an easy way to have a single Regex behave like you want. You can use a function to determine what to replace each character with, though:
// This should end up as 1232,4309 - allows one comma and any digits
let test = 'k12,3.2,,43,d0.9';
let foundComma = false;
let replaced = test.replace(/(,,)|[^\d]/g, function (item) {
if (item === ',' && !foundComma) {
foundComma = true;
return ',';
} else {
return '';
}
})
console.log(replaced);
This will loop through each non-digit. If its the first time a comma has appeared in this string, it will leave it. Otherwise, if it must be either another comma or a non-digit, and it will be replaced. It will also replace any double commas with nothing, even if it is the first set of commas - if you want it to be replaced with a single comma, you can remove the (,,) from the regex.
I may just be being thick here but I don't understand why I am receiving this error. Outside of the function the .test() works fine. But inside, I get the error. Was thinking it was something to do with the scope of the .test() function but am I just missing something blindingly obvious here?
function cFunctionfirst() {
firstField = document.getElementById("sname_input_first").value;
document.getElementById("demo").innerHTML = "first: " + firstField;
console.log(firstField);
var regex = "!##$£%^&*()+=[]\\\';,./{}|\":<>?";
if(regex.test(firstField)){
console.log('illegal characters used');
} else {
console.log('Character okay');
};
};
That's because regex is not a RegExp object, but just a string. It should be declared as such (remember to escape special characters using \):
var regex = /[!##\$£%\^&\*\(\)\+=\[\]\\\';,\.\/\{\}\|":<>\?]/;
Not only have I escaped some special regex characters, but you will need to wrap the entire selection inside unescaped [ and ] brackets, so that you test against a set of characters.
p/s: These are the set characters that need to be escaped: \ ^ $ * + ? . ( ) | { } [ ]
See proof-of-concept example:
function cFunctionfirst(value) {
var regex = /[!##\$£%\^&\*\(\)\+=\[\]\\\';,\.\/\{\}\|":<>\?]/;
if(regex.test(value)){
console.log('illegal characters used');
} else {
console.log('Character okay');
};
};
cFunctionfirst('Legal string');
cFunctionfirst('Illegal string #$%');
Alternatively, if you don't want to manually escape the characters, you can either use a utility method to do it, or use an ES6 non-regex approach, which is probably a lot less efficient: checkout the JSPerf test I have made. Simply add the blacklisted characters literally in a string, split it, and then use Array.prototype.some to check if the incoming string contains any of the blacklisted characters:
function cFunctionfirst(value) {
var blacklist = '!##$£%^&*()+=[]\\\';,./{}|":<>?'.split('');
if (blacklist.some(char => value.includes(char))) {
console.log('illegal characters used');
} else {
console.log('Character okay');
};
};
cFunctionfirst('Legal string');
cFunctionfirst('Illegal string #$%');
This should pass the condition:
syntax_search = (){return 0;}
syntax_search = ( ) { fsf return 0;}
syntax_search = ( ) { return 0; }
syntax_search = (){ return; }
syntax_search = (){ if(x){ sdfsdf } return 0;}
syntax_search = (){ char x[20]; return };
It is not passing all the combinations above, What is the right way?
if( /^\s*(\s*)\s*{[\s\S]*\s+return\s*[0-9]*\s*;\s*}\s*/.test(syntax_search) )
You regular expression contains many unneeded complexities and there are some characters that need escaping such as { and }.
Anyway you can use this modified version of your regex and it should work.
^\s*\(\s*\)\s*\{(.*(return\s*\d*\s*;)\s*)\}\s*;?$
// ^
// |
// There was a ? here
Regex 101 Demo
Some issues:
As M42 pointed out, you need to escape the curly brackets
The parentheses at the begining also need to be escaped (otherwise you are defining a capture group)
"return" is required by the expression. Your first 2 test cases don't contain the word return and will fail. Is that on purpose?
Same as #3 for ;.
[\s\S]* Anything which is a space and everything which isn't. Replace by a dot .* If you need to also match a newline, use [^]*
This regex is not anchored to the end of the string so it will allow invalid strings. (You can put anything you want after the last }
/^\s*(\s*)\s*{[^]return\s\d*\s*;\s*}\s*$/
How do I do a .match on a string that has parentheses in the string?
String1.match("How do I match this (MATCH ME)");
None of the answers are getting me what I want. I'm probably just doing it wrong. I tried to make my question basic and I think doing that asked my question wrong. This is the statement I am tring to fix:
$('[id$=txtEntry3]').focus(function () {
if (!DropdownList.toString().match($('[id$=txtEntry2]').val()) || $('[id$=txtEntry2]').val().length < 5) {
$('[id$=txtEntry2]').select();
ErrorMessageIn("The Ingredient number you entered is not valid.");
return;
}
ErrorMessageOut();
});
This works correctly the problem I am running into is when it tries to match a entry from "txtEntry2" that has "()" in it.
Well it's kinda broken but it works for what I need it to do. This is what I did to fix my problem:
$('[id$=txtEntry3]').focus(function () {
if (!StripParentheses(DropdownList).match(StripParentheses($('[id$=txtEntry2]').val())) || $('[id$=txtEntry2]').val().length < 5) {
$('[id$=txtEntry2]').select();
if (!$('[id$=txtEntry2]').val() == "") {
ErrorMessageIn("The Ingredient number you entered is not valid.");
}
return;
}
ErrorMessageOut();
});
function StripParentheses(String){
x = String.toString().replace(/\(/g, '');
x = x.toString().replace(/\)/g, '');
return x;
}
to get all occurences in e.g. ".. (match me) .. (match me too) .." add the g regexp flag
string.match(/\((.*?)\)/g)
this as also an advantage, that you get only list of all occurences. without this flag, the result will include a whole regexp pattern match (as the first item of resulting array)
If you are interested in the part of the string between parenthesis, then you can use /\(([^\)]*)\)/; if you just need to get the full string, then you can you can use /\([^\)]*\)/.
var str = "How do I match this (MATCH ME)";
str.match(/\((.*?)\)/);
I'm using startswith reg exp in Javascript
if ((words).match("^" + string))
but if I enter the characters like , ] [ \ /, Javascript throws an exception.
Any idea?
If you're matching using a regular expression you must make sure you pass a valid Regular Expression to match(). Check the list of special characters to make sure you don't pass an invalid regular expression. The following characters should always be escaped (place a \ before it): [\^$.|?*+()
A better solution would be to use substr() like this:
if( str === words.substr( 0, str.length ) ) {
// match
}
or a solution using indexOf is a (which looks a bit cleaner):
if( 0 === words.indexOf( str ) ) {
// match
}
next you can add a startsWith() method to the string prototype that includes any of the above two solutions to make usage more readable:
String.prototype.startsWith = function(str) {
return ( str === this.substr( 0, str.length ) );
}
When added to the prototype you can use it like this:
words.startsWith( "word" );
One could also use indexOf to determine if the string begins with a fixed value:
str.indexOf(prefix) === 0
If you want to check if a string starts with a fixed value, you could also use substr:
words.substr(0, string.length) === string
If you really want to use regex you have to escape special characters in your string. PHP has a function for it but I don't know any for JavaScript. Try using following function that I found from [Snipplr][1]
function escapeRegEx(str)
{
var specials = new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"); // .*+?|()[]{}\
return str.replace(specials, "\\$&");
}
and use as
var mystring="Some text";
mystring=escapeRegEx(mystring);
If you only need to find strings starting with another string try following
String.prototype.startsWith=function(string) {
return this.indexOf(string) === 0;
}
and use as
var mystring="Some text";
alert(mystring.startsWith("Some"));