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)
Related
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.
I am currently doing a regex comparison to remove words (rude words) from a text field when written by the user. At the moment it performs the check when the user hits space and removes the word if matches. However it will remove the word even if it is part of another word. So if you type apple followed by space it will be removed, that's ok. But if you type applepie followed by space it will remove 'apple' and leave pie, that's not ok. I am trying to make it so that in this instance if apple is part of another word it will not be removed.
Is there any way I can perform the comparison on the whole word only or ignore the comparison if it is combined with other characters?
I know that this allows people to write many rude things with no space. But that is the desired effect by the people that give me orders :(
Thanks for any help.
function rude(string) {
var regex = /apple|pear|orange|banana/ig;
//exaple words because I'm sure you don't need to read profanity
var updatedString = string.replace( regex, function(s) {
var blank = "";
return blank;
});
return updatedString;
}
$(input).keyup(function(event) {
var text;
if (event.keyCode == 32) {
var text = rude($(this).val());
$(this).val(text);
$("someText").html(text);
}
}
You can use word boundaries (\b), which match 0 characters, but only at the beginning or end of a word. I'm also using grouping (the parentheses), so it's easier to read an write such expressions.
var regex = /\b(apple|pear|orange|banana)\b/ig;
BTW, in your example you don't need to use a function. This is sufficient:
function rude(string) {
var regex = /\b(apple|pear|orange|banana)\b/ig;
return string.replace(regex, '');
}
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);
}
});
I'm trying to remove the whitespaces from a textarea . The below code is not appending the text i'm selecting from two dropdowns. Can somebody tell me where i'd gone wrong? I'm trying to remove multiple spaces within the string as well, will that work with the same? Dont know regular expressions much. Please help.
function addToExpressionPreview() {
var reqColumnName = $('#ddlColumnNames')[0].value;
var reqOperator = $('#ddOperator')[0].value;
var expressionTextArea = document.getElementById("expressionPreview");
var txt = document.createTextNode(reqColumnName + reqOperator.toString());
if (expressionTextArea.value.match(/^\s+$/) != null)
{
expressionTextArea.value = (expressionTextArea.value.replace(/^\W+/, '')).replace(/\W+$/, '');
}
expressionTextArea.appendChild(txt);
}
> function addToExpressionPreview() {
> var reqColumnName = $('#ddlColumnNames')[0].value;
> var reqOperator = $('#ddOperator')[0].value;
You might as well use document.getElementById() for each of the above.
> var expressionTextArea = document.getElementById("expressionPreview");
> var txt = document.createTextNode(reqColumnName + reqOperator.toString());
reqOperator is already a string, and in any case, the use of the + operator will coerce it to String unless all expressions or identifiers involved are Numbers.
> if (expressionTextArea.value.match(/^\s+$/) != null) {
There is no need for match here. I seems like you are trying to see if the value is all whitespace, so you can use:
if (/^\s*$/.test(expressionTextArea.value)) {
// value is empty or all whitespace
Since you re-use expressionTextArea.value several times, it would be much more convenient to store it an a variable, preferably with a short name.
> expressionTextArea.value = (expressionTextArea.value.replace(/^\W+/,
> '')).replace(/\W+$/, '');
That will replace one or more non-word characters at the end of the string with nothing. If you want to replace multiple white space characters anywhere in the string with one, then (note wrapping for posting here):
expressionTextArea.value = expressionTextArea.value.
replace(/^\s+/,'').
replace(/\s+$/, '').
replace(/\s+/g,' ');
Note that \s does not match the same range of 'whitespace' characters in all browsers. However, for simple use for form element values it is probably sufficient.
Whitespace is matched by \s, so
expressionTextArea.value.replace(/\s/g, "");
should do the trick for you.
In your sample, ^\W+ will only match leading characters that are not a word character, and ^\s+$ will only match if the entire string is whitespace. To do a global replace(not just the first match) you need to use the g modifier.
Refer this link, you can get some idea. Try .replace(/ /g,"UrReplacement");
Edit: or .split(' ').join('UrReplacement') if you have an aversion to REs
I would like some help creating a regular expression for parsing a string on a textbox. I currently have these two javascript methods:
function removeIllegalCharacters(word) {
return word.replace(/[^a-zA-Z 0-9,.]/g, '');
}
$("#comment").keyup(function() {
this.value = removeIllegalCharacters(this.value);
});
I would like to replace my /[^a-zA-Z 0-9,.]/g regex for one that would accept only the following set of characters:
a-z
A-Z
0-9
áéíóúü
ÁÉÍÓÚÜ
ñÑ
;,.
()
- +
It's probably pretty simple, but I have close to none regex skills. Thanks in advance.
Just add those characters in.
function removeIllegalCharacters(word) {
return word.replace(/[^a-zA-Z 0-9,.áéíóúüÁÉÍÓÚÜñÑ();+-]/g, '');
}
return word.replace(/[^a-zA-Z0-9áéíóúüÁÉÍÓÚÜñÑ\(\);,\.]/g, '');
You may have to use the hex escape sequence (\x##) or unicode escape sequence (\u####) for some of the non standard letters, but that will give you a good start. Or, slightly simplified:
return word.replace(/[^\w\dáéíóúüÁÉÍÓÚÜñÑ\(\);,\.]/g, '');
If I've understood your requirements correctly, you want to allow only the listed char and you want to delete rest all char. If that is the case you can simply extend your char class as:
function removeIllegalCharacters(word) {
return word.replace(/[^a-zA-Z0-9áéíóúüÁÉÍÓÚÜñÑ;,.()]/g, '');
}
Did you try with: [^a-zA-Z 0-9;,.áéíóúüÁÉÍÓÚÜñÑ()]