javascript regular expression , what am I doing wrong? - javascript

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.

Related

Use only one of the characters in regular expression javascript

I guess that should be smth very easy, but I'm stuck with that for at least 2 hours and I think it's better to ask the question here.
So, I've got a reg expression /&t=(\d*)$/g and it works fine while it is not ?t instead of &t in url. I've tried different combinations like /\?|&t=(\d*)$/g ; /\?t=(\d*)$|/&t=(\d*)$/g ; /(&|\?)t=(\d*)$/g and various others. But haven't got the expected result which is /\?t=(\d*)$/g or /&t=(\d*)$/g url part (whatever is placed to input).
Thx for response. I think need to put some details here. I'm actually working on this peace of code
var formValue = $.trim($("#v").val());
var formValueTime = /&t=(\d*)$/g.exec(formValue);
if (formValueTime && formValueTime.length > 1) {
formValueTime = parseInt(formValueTime[1], 10);
formValue = formValue.replace(/&t=\d*$/g, "");
}
and I want to get the t value whether reference passed with &t or ?t in references like youtu.be/hTWKbfoikeg?t=82 or similar one youtu.be/hTWKbfoikeg&t=82
To replace, you may use
var formValue = "some?some=more&t=1234"; // $.trim($("#v").val());
var formValueTime;
formValue = formValue.replace(/[&?]t=(\d*)$/g, function($0,$1) {
formValueTime = parseInt($1,10);
return '';
});
console.log(formValueTime, formValue);
To grab the value, you may use
/[?&]t=(\d*)$/g.exec(formValue);
Pattern details
[?&] - a character class matching ? or &
t= - t= substring
(\d*) - Group 1 matching zero or more digits
$ - end of string
/\?t=(\d*)|\&t=(\d*)$/g
you inverted the escape character for the second RegEx.
http://regexr.com/3gcnu
I want to thank you all guys for trying to help. Special thanks to #Wiktor Stribiżew who gave the closest answer.
Now the piece of code I needed looks exactly like this:
/[?&]t=(\d*)$/g.exec(formValue);
So that's the [?&] part that solved the problem.
I use array later, so /\?t=(\d*)|\&t=(\d*)$/g doesn't help because I get an array like [t&=50,,50] when reference is & type and the correct answer [t?=50,50] when reference is ? type just because of the order of statements in RegExp.
Now, if you're looking for a piece of RegExp that picks either character in one place while the rest of RegExp remains the same you may use smth like this [?&] for the example where wanted characters are ? and &.

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

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

Regular Expression Guidance needed for Javascript

In the following input string:
{$foo}foo bar \\{$blah1}oh{$blah2} even more{$blah3} but not{$blarg}{$why_not_me}
I am trying to match all instances of {$SOMETHING_HERE} that are not preceded by an unescaped backslash.
Example:
I want it to match {$SOMETHING} but not \{$SOMETHING}.
But I do want it to match \\{$SOMETHING}
Attempts:
All of my attempts so far will match what I want except for tags right next to each other like {$SOMETHING}{$SOMETHING_ELSE}
Here is what I currently have:
var input = '{$foo}foo bar \\{$blah1}oh{$blah2} even more{$blah3} but not{$blarg}{$why_not_me}';
var results = input.match(/(?:[^\\]|^)\{\$[a-zA-Z_][a-zA-Z0-9_]*\}/g);
console.log(results);
Which outputs:
["{$foo}", "h{$blah2}", "e{$blah3}", "t{$blarg}"]
Goal
I want it to be :
["{$foo}", "{$blah2}", "{$blah3}", "{$blarg}", "{$why_not_me}"]
Question
Can anybody point me in the right direction?
The problem here is that you need a lookbehind, which JavaScript Regexs don't support
basically you need "${whatever} if it is preceded by a double slash but not a single slash" which is what the lookbehind does.
You can mimic simple cases of lookbehinds, but not sure if it will help in this example. Give it a go: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript
edit
Btw, I don't think you can do this a 'stupid way' either because if you have [^\\]\{ you'll match any character that is not a backslash before the brace. You really need the lookbehind to do this cleanly.
Otherwise you can do
(\\*{\$[a-zA-Z_][a-zA-Z0-9_]*\})
Then just count the number of backslashes in the resulting tokens.
When all else fails, split, join/replace the crap out of it.
Note: the first split/join is actually the cleanup portion. That kills \{<*>}
Also, I didn't account for the stuff inside the brackets since there's code for that already.
var input = '{$foo}foo bar \\{$blah1}oh{$blah2} even more\\\\{$blah3} but not{$blarg}{$why_not_me}';
input.split(/(?:[^\\])\\\{[^\}]*\}/).join('').replace(/\}[^\{]*\{/g,'},{').split(/,/));
This seems to do what I want:
var input = '{$foo}foo bar \\{$blah1}oh{$blah2} even more\\\\{$blah3} but not{$blarg}{$why_not_me}';
var results = [];
input.replace(/(\\*)\{\$[a-z_][a-z0-9_]*\}/g, function($0,$1){
$0 = $0.replace(/^\\\\/g,'');
var result = ($0.indexOf('\\') === 0 ? false : $0);
if(result) {
results.push(result);
}
})
console.log(results);
Which gives:
["{$foo}", "{$blah2}", "{$blah3}", "{$blarg}", "{$why_not_me}"]

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)

How to replace whitespaces using javascript?

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

Categories

Resources