My main syntax checker condition is not passing all my string combinations - javascript

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*$/

Related

Javascript remove all characters by regex rules

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.

Why am I getting 'Uncaught TypeError: regex.test is not a function' when used inside another function?

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 #$%');

Identifying "." and absence of whitespace in a string through "if ... if"

I want to identify whether, in a string, there is no whitespace after "."
I tried a nested if statement, but it doesn't work. I guess I am missing something really simple.
Also, I read Regex might do this, but I couldn't wrap my head around the syntax.
(function() {
'use strict';
var invocationInitial = document.getElementById('spokenNames');
if(invocationInitial) {
var invocation = invocationInitial.innerHTML.trim();
}
var counter = 1;
var message = '';
if(invocation.indexOf('.') !== -1) {
if(/\s/.test(invocationInitial) === false)
{
message = counter + ". No dot in string without subsequent whitespace";
counter = counter +1;
}
}
if(message) {
alert(message);
}
})();
A browser warning ("message") should be displayed if "invocationInitial" does not have every every occuring dot (".") followed by a whitespace.
var counter is introduced here, because in the full version, multiple browser warnings will be shown based on different conditions.
The RegEx you need here is pretty simple: /\.\S/ . That says "match a dot not followed by a whitespace character". Note that \s means "match a whitespace character" while \S (capital S) means "match anything that is NOT a whitespace character".
So you can simply do this:
if (/\.\S/.test(invocation)) {
// There's a dot followed by non-whitespace!
}
else {
// There is no dot followed by non-whitespace.
}

I would like to add javascript regexp satisfying my concerns

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.

startswith in javascript error

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"));

Categories

Resources