Javascript Dynamic Regex Generation - javascript

I want to make my alphanumeric regex dynamic in a way that it takes the allowed special characters with it as an argument by the user. Following is my code ... I am getting quotes error here .... any body can tell me how to go about it ?
function aplhanumeric(value,allowed){
///^[a-z0-9_\-]+$/i
alert(allowed);
if(allowed != ''){
var regex = new RegExp('/^[a-z0-9_\' + allowed + ']+$/i');
return (value.match(regex));
}else{
return (alphaNumericRegex.test(value));
}
}

You've actually escaped the quote, so you have to escape the escape
var regex = new RegExp("^[a-z0-9_\\" + allowed + "]+$", "i");

Related

Javascript replace regex any character

I am trying to replace something like '?order=height' and I know it can be easily done like this:
data = 'height'
x = '?order=' + data
x.replace('?order=' + data, '')
But the problem is that question mark can sometimes be ampersand.. What I really wish to do is make blank whether the first character is ampersand or question mark so basically whether
?order=height
&order=height
can be made a blank string
x.replace(/[&?]order=height/, '')
If data is string variable
x.replace(/[&?]order=([^&=]+)/, '')
Use regex for that .replace(/[?&]order=height/, '')
[?&] means any character from this list.
/ is start and end delimiter.
Please note that pattern is not enclosed as string with ' or ".
This is how you may do it. Create a RegExp object with
"[&?]order=" + match
and replace with "" using String.prototype.replace
function replace(match, str) {
regex = new RegExp("[&?]order=" + match,"g")
return str.replace(regex, "")
}
console.log(replace("height", "Yo &order=height Yo"))
console.log(replace("weight", "Yo ?order=weight Yo"))
console.log(replace("age", "Yo ?order=age Yo"))

Regex for empty string or white space

I am trying to detect if a user enter whitespace in a textbox:
var regex = "^\s+$" ;
if($("#siren").val().match(regex)) {
echo($("#siren").val());
error+=1;
$("#siren").addClass("error");
$(".div-error").append("- Champ Siren/Siret ne doit pas etre vide<br/>");
}
if($("#siren").val().match(regex)) is supposed to match whitespace string, however, it doesn' t seems to work, what am I doing wrong ?
Thanks for your helps
The \ (backslash) in the .match call is not properly escaped. It would be easier to use a regex literal though. Either will work:
var regex = "^\\s+$";
var regex = /^\s+$/;
Also note that + will require at least one space. You may want to use *.
If you are looking for empty string in addition to whitespace you meed to use * rather than +
var regex = /^\s*$/ ;
^
If you're using jQuery, you have .trim().
if ($("#siren").val().trim() == "") {
// it's empty
}
If one only cares about whitespace at the beginning and end of the string (but not in the middle), then another option is to use String.trim():
" your string contents ".trim();
// => "your string contents"
http://jsfiddle.net/DqGB8/1/
This is my solution
var error=0;
var test = [" ", " "];
if(test[0].match(/^\s*$/g)) {
$("#output").html("MATCH!");
error+=1;
} else {
$("#output").html("no_match");
}
Had similar problem, was looking for white spaces in a string, solution:
To search for 1 space:
var regex = /^.+\s.+$/ ;
example: "user last_name"
To search for multiple spaces:
var regex = /^.+\s.+$/g ;
example: "user last name"

Replacing all symbols in a javascript string

Hi all ia m trying to replace all characters of "+" in a string by using the code below:
var findValue = "+";
var re = new RegExp(findValue, 'g');
searchValueParam = searchValueParam.replace(re, " ");
However i recieve this exception:
SyntaxError: Invalid regular expression: nothing to repeat
previously i applied just searchValueParam = searchValueParam.replace("+", " "); but that only replaces the first occurrence, not all.
Any suggestions?
For multiple replacements you need to use regex with the global (g) modifier, however + has a special meaning (the previous item 1 or more times), so it needs to be escaped.
searchValueParam = searchValueParam.replace(/\+/g,' ');
You need to escape the + sign:
searchValueParam.replace(/\+/g, " ");
If you want to keep the code you have, replace
var findValue = '+';
with
var findValue = '\\+';
Plus has a special meaning (quantifier) in a regular expression. This is why we need to escape it with a backslash: \+. However, when you place this in a string, the backslash itself has to be escaped as it has a special meaning in a string. This is how we end up with '\\+'.
In conclusion, this
var re = new RegExp('\\+', 'g')
is equivalent to this
var re = /\+/g;

Am I using pattern matching correctly here?

I have the following code. Given that the variable u1 can be any of the following:
NBSLoan|Accept|PPI+No|60Months
NBSLoan|Refer|PPI+No|60Months
DeBSLoan|Accept|PPI+No|60Months
Also, the last part 60Months will always be different, can I pattern match using the following JavaScript? Do I need to put in a special character for the pipe | symbol? Or will this not work as I'm trying to match only the first part of a longer string?
<script type="text/javascript">
var u1 = 'NBSLoan|Accept|PPI+No|60Months';
var n_accept = /^NBSLoan|Accept$/;
var n_refer = /^NBSLoan|Refer$/;
var d_accept = /^DeBSLoan|Accept$/;
if (u1.match(n_accept)) {
var pvnPixel = '<img src="https://url1.com"/>';
document.write(pvnPixel);
}
else if (u1.match(n_refer)) {
var pvnPixel2 = '<img src="url2.com"/>';
document.write(pvnPixel2);
}
else if (u1.match(d_accept)) {
var pvnPixel3 = '<img src="url3.com"/>';
document.write(pvnPixel3);
}
</script>
Do I need to put in a special character for the pipe | symbol? Or will this not work as I'm trying to match only the first part of a longer string?
Both.
You need to escape the pipe symbol with a backslash to match a literal pipe character. Without the backslash it means alternation.
You also need to remove your end of line anchor.
Try this regular expression:
/^NBSLoan\|Accept/
Why don't you first split fields with split('|'):
function dispatch(u) {
var parts = u.split('|'),
key = parts[0] + "_" + parts[1];
disp_table = {
'NBSLoan_Accept':'url1.com',
'NBSLoan_Refer':'url2.com',
'DeBSLoan_Accept':'url3.com'
},
url = disp_table[key];
url && document.write("<img src=\""+url+"\"/>");
}
You want to also remove the $ (it signifies the end of string) or add a .* to capture all the other characters:
To lose the end:
/^NBSLoan\|Accept/
To match and capture the other characters:
/^NBSLoan\|Accept.*$/

How do you safely wrap a JS string variable in double quote chars?

Obviously when you're creating an actual string literal yourself, you backslash escape the double quote characters yourself.
var foo = "baz\"bat";
Just as you would with the handful of other control characters, like linebreaks and backslashes.
var bar = "baz\\bat\nmynew line and a \"quote\" ";
but if you're just wrapping that existing variable in quote character, ie to give it to some other system that requires quoted input, there's some confusion.
Obviously you have to escape any potential double quote characters that are in the string.
var doubleQuoteRe = /\"/g;
var quoted = "\"" + unquoted.replace(escaper, '\\\"') + "\"";
But according to some you also now have to worry about escaping literal backslash characters in the variable. In other words using much bigger hammer than my little regex. However i dont see why.
You might want to avoid escaping quotes you already escaped-
String.prototype.inquotes=function(){
return '"'+this.replace(/(^|[^\\])"/g,'$1\\"')+'"';
}
The answer is that yes, you have to do two things:
replace literal backslash characters in the string, with two backslashes,
THEN, you proceed replacing any occurrences of " with \".
the simplest explanation for why step 1 is essential, is to consider the 5-character string :
foo\"
After the first 3 characters (foo), there is a literal backslash character in the string, and then there is a literal double quote character.
(Put another way, as a string literal this would look like "foo\"")
If I were to only replace the quote character, i'd end up with a quoted string whose value was
foo\\"
But the two backslashes here will be interpreted as a single backslash. So when I wrap this value in quotes, I end up with unbalanced quotes.
"foo\\""
on the other hand, if I do step 1 first -- replacing all backslashes with double backslashes gives
foo\\"
and then step 2 -- replacing the quote with slash-quote gives
foo\\\"
Now when i wrap my value in quote characters i finally get
"foo\\\""
which is correct.
There is a non standard str.quote() in FF
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/quote
They suggest the following polyfill
if(!String.prototype.quote){
// oop version - no dependencies
String.prototype.quote = (function(){
// prepare fallback
// ----------------
// backslash escape double quotes and backslashes
var escp_regex = /[\\"]/g,
escp_callback = '\\$&',
// escape control characters
ctrl_map = {
'\b': '\\b', // backspace
'\t': '\\t', // tab
'\n': '\\n', // new line
'\f': '\\f', // form feed
'\r': '\\r' // carriage return
},
// don't rely on `Object.keys(ctrl_map).join('')`
ctrl_regex = new RegExp('[\b\t\n\f\r]', 'g'),
ctrl_callback = function(match){
return ctrl_map[match];
},
// hex-escape, spare out control characters and ASCII printables
// [0-7,11,14-31,127-255]
xhex_regex = /[\x00-\x07\x0B\x0E-\x1F\x7F-\xFF]/g,
xhex_callback = function(match, char_code){
char_code = match.charCodeAt(0);
return '\\x' + (char_code < 16 ? '0' : '') + char_code;
},
// hex-escape all others
uhex_regex = /[\u0100-\uFFFF]/g,
uhex_callback = function(match, char_code){
char_code = match.charCodeAt(0);
return '\\u' + (char_code < 4096 ? '0' : '') + char_code;
},
// delegate to native `JSON.stringify` if available
stringify = typeof JSON !== 'undefined' && JSON.stringify;
// return actual polyfill
// ----------------------
return function(){
var self = this; // promote compression
if(self == null) throw new TypeError('can\'t convert ' + self + ' to object');
if(stringify) return stringify(self);
return '"' + self
.replace(escp_regex, escp_callback)
.replace(ctrl_regex, ctrl_callback)
.replace(xhex_regex, xhex_callback)
.replace(uhex_regex, uhex_callback) + '"';
}
}());
// generic version - requires Function#bind
String.quote = Function.call.bind(''.quote);
}
You might want to escape other characters aside from quotes, eg whitespace characters (newlines!) and/or non-ASCII characters. There's Crockford's quote(), and my own implementation can be found at mercurial.intuxication.org.

Categories

Resources