Regex is confusing me and why won't it parse properly? - javascript

Sorry about the confusing title. I'm new to Regex and JS/JQ in general. However, I'm trying to parse this. Basically, I want it to add the key pressed to the HTML if and ONLY if the keys 0-9 and the keys +, -, /, and * are pressed. Any help would be much appreciated. Here is my code:
function charCode(code) {
return String.fromCharCode(code);
}
function escapeChars(esc) {
return esc.replace(/[0-9\+-\*\/]*$/, "");
}
$('#tb').html("0");
$(document).on("keydown", function(event) {
var div = $('#tb');
var which = event.which;
which = charCode(which);
which = escapeChars(which);
else if (div.html() == "0") {
//alert("Div is equal to 0."); --Debug
div.html(which);
} else {
//alert("Div is equal to " + div.html()); --Debug
div.html(div.html() + which);
}
});
Currently, it doesn't allow anything through.

There's a couple problems with your regular expression.
You want to replace characters that do not match your list. To do that, you start your character class ([]) with a ^.
You don't need to escape + or * in the regular expression. You do need to move the - to the beginning or end though.
You don't need the * or the $ after the character class. Dropping those, you'll replace any character that doesn't match, no matter where it occurs in the string.
In case your string contains more than one character (may not apply here), adding a g flag to the end will allow you to replace all characters that do not match.
That results in a regular expression that looks like this:
/[^0-9+*\/-]/g
This fiddle shows the above regular expression working: http://jsfiddle.net/WyttT/
Updated
Another problem you're encountering is caused by checking keycodes from a keydown event. The keycodes on keydown do not match to actual ascii character codes, so non-alphanumeric keys are getting converted into weird characters. If you change your even handler to respond tokeypress instead, you'll get better results.

I don't think you want a regex for this. I think charAt() will do what you want far more simply.
You have a character. You have a list of characters which either match it or don't. charAt() does that simply and efficiently.

Now that jcsanyi has helped you with the regex, here is a simplification of your JS code. Codepen
You will want to use keypress instead of keydown/keyup, otherwise your numpad will return the wrong keys, and anything requiring a shift (shift+8 = * for instance) won't work. You can also use RegExp.test(String) to check if the character is valid, and div.append(char) in place of div.html(div.html + char).
var div = $('#tb');
$(document).on("keypress", function(event) {
var char = String.fromCharCode(event.which);
if (/[0-9+*\/-]/.test(char) === true) {
div.append(char);
}
});

Related

.replace() is not working like it should

I am trying to toggle a hidden input element when the select element has a certain option. When I am alerted of variable q, q has no input but variable put does I am quite confused as to why .replace() removes the entire string.
function hiddeninput(choice, put) {
var q = put.replace(/./g, "").replace(/#/g, "");
alert(put + "," + q);//alerts .other,
if (choice === q) {
$(put).show();
} else {
$(put).hide();
}
}
Any help would be appreciated. JSfiddle has been quite buggy these past few days some of my previous working fiddles have stopped working, maybe that could be the reason.
Do you realize that . is to match any character?
You need to escape it with a \ so it will match just the . and not any character.
var q = put.replace(/\./g, "").replace(/#/g, "");
And instead of doing two replacements you can just do one
var q = put.replace(/[.#]/g,"");
In regex "." will match any character. You've got: put.replace(/./g, "");. This means you're replacing each match of any character with nothing, which will result in nothing.
If you want to match a dot, you need to escape the special character using a backslash: put.replace(/\./g, "");.
I'm not sure if this'll entirely solve your problem, but to me it seems like something unintended.

ASCII character not being recognized in if statement

I am trying to get a string from a html page with jquery and this is what I have.
var text = $(this).text();
var key = text.substring(0,1);
if(key == ' ' || key == ' ')
key = text.substring(1,2);
text is this  Home
And I want to skip the space and or the keycode above It appears this code does not work either. It only gets the text.substring(0,1); instead of text.substring(1,2); because the if statement is not catching.= and I am not sure why. Any help would be super awesome! Thanks!
There are several problems with the code in the question. First,   has no special meaning in JavaScript: it is a string literal with six characters. Second, text.substring(1,2) returns simply the second character of text, not all characters from the second one onwards.
Assuming that you wish to remove one leading SPACE or NO-BREAK SPACE (which is what   means in HTML; it is not an Ascii character, by the way), then the following code would work:
var first = text.substring(0, 1);
if(first === ' ' || first === '\u00A0') {
text = text.substring(1, text.length);
}
The notation \u00A0 is a JavaScript escape notation for NO-BREAK SPACE U+00A0.
Should you wish to remove multiple spaces at the start, and perhaps at the end too, some modifications are needed. In that case, using a replace operation with regular expression is probably best.
If you want remove spaces at the beginning (and end) of a string, you can use the trim function
var myvar = " home"
myVar.trim() // --> "home"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

jQuery regex test in .each error

Ok, so I have multiple inputs that receive UUID codes. So Im using the .each function from jQuery to go one by one and validate the input to be a UUID code. So this is the code that I have until now:
function validateAll(){
var regex = /^[a-zA-Z0-9]{8}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{12}$/ig;
$('input.offer').each(function(x){
if($(this).val() !== ""){
console.log(x+" - "+$(this).val()+" - "+regex.test($(this).val()));
}
});
return true;
}
Now when I run this with two inputs being: 00000000-0000-0000-0000-000000000000 this is what I get in the console:
0 - 00000000-0000-0000-0000-000000000000 - true
1 - 00000000-0000-0000-0000-000000000000 - false
Why the regex.test() is validating the first one but not second one? Thanks.
You need to bring the regex instantiation within the loop - it cannot be retested against another string.
function validateAll(){
$('input.offer').each(function(x) {
var regex = /^[a-zA-Z0-9]{8}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{12}$/ig;
if($(this).val() !== ""){
console.log(x + " - " + $(this).val() + " - " + regex.test($(this).val()));
}
});
return true;
}
Example fiddle
The reason the second iteration fails:
when [the regex] is a global regular expression. It will attempt to match from the index of the last match in any previous string.
Article: Be careful when reusing regex objects
Remove the g modifier from the regexp. When you reuse a regexp with this modifier, it starts the new test from the index of the last match, rather than the beginning of the new string. This modifier serves no purpose when using Regex::test, since it only tells you if the regexp matches anywhere -- multiple matches are redundant. So it should be:
var regex = /^[a-zA-Z0-9]{8}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{12}$/i;
Also, I wonder why you put both a-z and A-Z in your character classes when you also use the i modifier to make it case-insensitive.
FIDDLE

javascript regular expression , what am I doing wrong?

var regExpress = "/^([a-zA-Z0-9\!\#\#\$\%\^\&\*\(\)\-\+\=\|\}\{'\"\;\:\?\/\.\,\s]*)/i";
if (strMessage.search(regExpress) == -1) { alert("error occurs"); }
I want to allow almost all characters.
I want to use it because of some formatting issue from some other application.
So whenever user cuts and pastes from another application,
it causes to add some weird character which I need to take care of it.
But every time I am getting -1 return which is not correct.
What is wrong in this regular expression?
Don't double quote the expression, remove the quotes, ie:
var regex = /.../i;
var myNewString = strMessage.replace(/[^A-Z0-9]+/i, "");
Replace the characters inside the brackets after the ^ with whatever you want to allow.

jQuery input filter for textarea

I adapted this solution into my script. The idea is to prevent the user from typing unauthorized characters (of course there is also a filter on the back end).
$('#someinput').keyup(function() {
var $th = $(this);
$th.val( $th.val().replace(/[^a-zA-Z0-9]/g, function(str) {
console.log(str);
return '';
}))
})
It works nice, but I also need the users to be able to type specific allowed characters like: .,!?ñáéíóú - I mean, the basic a-zA-Z0-9 plus some basic chars and the whole bunch of special language characters.
What actually needs to be left out are: ##$%^&*()=_+"':;/<>\|{}[]
Any ideas? Thanks!
Solution thanks to Michael
//query
$('#someinput').keyup(function() {
var $th = $(this);
$th.val($th.val().replace(/[##$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g,function(str){return '';}));
}).bind('paste',function(e) {
setTimeout(function() {
$('#someinput').val($('#someinput').val().replace(/[##$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g,function(str){return '';}));
$('#someinput').val($('#someinput').val().replace(/\s+/g,' '));
},100);
});
Invert your regular expression to only replace the specific characters you want omitted:
$th.val( $th.val().replace(/\s?[##$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g, ""));
// Edit: added optional \s to replace spaces after special chars
Note, a few of them need to be escaped with a backslash inside a [] character class: \\\[\]\^\/
If I'm understanding what you are wanting to do, can't you just add those unwanted characters to your regex instead of doing the [^a-zA-Z0-9]?
Replace that with [##\$%\^&\*\(\)=_\+"':;\/<>\\\|\{\}\[\]] (notice the escaping)

Categories

Resources