Javascript Regex as a string not working [duplicate] - javascript

This question already has answers here:
JavaScript RegExp objects
(5 answers)
Closed 7 years ago.
I am trying to understand why writing regex as a string is not working but using it without string does work.
this is my example:
var patt = new RegExp("/test_.*/gi");
var res = patt.test("test_4");
console.log(res);
will return false
but this:
var patt = /test_.*/gi;
var res = patt.test("test_4");
console.log(res);
will return true
what is the difference

Your syntax of RegExp is wrong.
The delimiters are not required when you use RegExp constructor to create new Regular Expression.
The flags should be passed as second parameter to the RegExp constructor.
And . should to be escaped, if you want to match . literal.
Usage
var patt = new RegExp("test_.*", "gi");
Demo
var patt = new RegExp("test_.*", "gi");
var res = patt.test("test_4");
document.write(res);

The regexp constructor does not need delimiters, also, flags are isolated in another argument which simplifies it to
var patt = new RegExp('test_.*', 'gi');
var res = patt.test("test_4");
console.log(res);

You do not need to include the / at the start and end of the regular expression when using the constructor and the flags need to be in the second argument. See the MDN Documentation for RegExp.
var patt = new RegExp( "test_.*", "gi" );
var res = patt.test("test_4");
console.log(res);

You are not calling the constructor correctly, the falgs should be passed as a second parameter:
new RegExp('test_.*', 'gi');
As you can see in Documentation, it should respect this format:
new RegExp(pattern[, flags])
This is your demo:
var patt = new RegExp("test_.*", 'gi');
var res = patt.test("test_4");
alert(res);

Related

Replace Javascript is not working

I'm trying to replace more than 1 word in same string, with RegExp, but it seems is not working, i tryied some answers here in stackoverflow, but with no result
var _tpl = "time working $times, not now $times"
var reg = "$times"
var regexp = new RegExp(reg, "g")
var replaceFor = 1
var _newTpl = _tpl.replace(regexp, replaceFor)
console.log(_newTpl)
some advice?
$ is a special character in a regular expression: you must escape it.
var _tpl = "time working $times, not now $times"
var reg = "\\$times"
var regexp = new RegExp(reg, "g")
var replaceFor = 1
var _newTpl = _tpl.replace(regexp, replaceFor)
console.log(_newTpl)
Note that you need two \s in order to put a single literal \ in the resulting string. If you create the regular expression directly, with regex syntax and not string syntax, only use one \:
const regexp = /\$times/g;
You have to escape regex' special characters before passing them to new RegExp.
var reg = "\\$times"
var _tpl = "time working $times, not now $times"
var reg = "\\$times"
var regexp = new RegExp(reg,"g")
var replaceFor = 1
var _newTpl = _tpl.replace(regexp, replaceFor)
console.log(_newTpl)

jQuery Regex from String

I have the following Regex that comes from a data Attribute on an HTML Element:
/^$|^[0-9]{2}.[0-9]{4}$/g
When I (manually) do:
/^$|^[0-9]{2}.[0-9]{4}$/g.test('01.2012');
It works and returns true.
When I put the Regex in a Variable like so:
var inputRegex = $(this).attr('data-validation');
And do:
inputRegex.test(input);
I get:
inputRegex.test is not a function.
I know that this is because inputRegex is a String and String does not have a test function, but when I create a RegExp object (new RegExp($(this).attr('data-validation')) it breaks my Regular Expression by escaping:
/\/^$|^[0-9]{2}.[0-9]{4}$\/g/
How can I use the data-attribute value as a Regular Expression? Please note that I cannot do: var regex = new RegExp(string, 'g'); because the Regular Expression(s) come predefined from the attribute.
var pattern = '\d+';
var regExp = new RegExp(pattern, 'g');
'1234dasf13241234'.match(regExp)
is it what you need?
var pattern = $(this).attr('data-validation');;
var regExp = new RegExp(pattern, 'g');
regExp.test(input);
in your case
your problem is that you need to retrieve the regex pattern from a attribute of an element, but it is returning string, and you want the string value to be like inline on your javascript code, like declaring plainly a regex. If this is really what you want to achieve, the closest solution is to use eval function, see updated code below:
var stringreg = "var inputRegex =" + $("#test").attr('data-validation') + ";"
eval(stringreg);
inputRegex.test(input);
This could help
var validation = "/^$|^[0-9]{2}.[0-9]{4}$/g"; //$(this).attr('data-validation')
var startIndex = validation.indexOf('/')+1
var lastIndex = validation.lastIndexOf('/');
var pattern = validation.substring(startIndex,lastIndex);
var options = validation.substring(lastIndex+1);
var regExp = new RegExp(pattern, options);
regExp.test('01.2012');
// true

matching values stored in variables or array with string javascript regex

Im trying to find a patterns in the sentence for regex matching.. in the code below result contains a string and we are checking if the word apple is present in it.
var patt = /apple/gi;
var newResult = patt.test(result);
I found the above code from a used case.. But i was wondering if i have more than one values and i want to check it in the string result, lets say an array with values var arr=["apple", "orange"] var patt=/arr[0]/gi will not work.. what could be the way in that scenario??
To check multiple entries, you can use the OR operator:
var patt = /apple|orange/gi;
var newResult = patt.test(result);
if you have a variable, you can do the below, IF(!) your key is regexp safe of course (that is, it doesn't contains characters which have meaning in regexp syntax):
var key = "apple";
var patt = new RegExp(key, 'gi');
var newResult = patt.test(result);
Although in this case, you might as well use indexOf:
var key = "apple";
var newResult = result.indexOf(key) > -1;
To use a string for your regex expressions, you need to create the regex using the regex constructor.
var pattern = "apple|orange";
var regex = new RegExp(pattern, "g"); // g is for global match
Read more about it here: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions

Match returning null in JavaScript

var regEx = new RegExp("/[0-9]/");
var test = 'TREE'
alert(test.match(regEx));
or
var regEx = new RegExp("/[0-9]/");
var test = '1234'
alert(test.match(regEx));
Why do they return null?
Am i missing something here?
(Ok, the debate mentally drained me last night)
When you are using new RegExp, you don't need the delimiters (/).
var regEx = new RegExp("[0-9]");
var test = '1234'
alert(test.match(regEx));
You only need the slashes if you are using a regex literal (which I prefer using to new RegExp).
var regEx = /[0-9]/;
var test = '1234'
alert(test.match(regEx));
To declare a RegExp:
var patt=new RegExp(pattern,modifiers);
or
var patt=/pattern/modifiers;
So try this:
var regEx = /[0-9]/g;
var test = '1234';
alert(test.match(regEx));

Javascript array string to regex literal

I have a working example here: http://jsfiddle.net/R7KuK/
I've tried to create an array containing full regular expressions with regex delimiters and set flags, but the RegExp object parses given strings as strings, not as regular expressions.
var regex = "/wolves/i"
vs.
var regex = /wolves/i
My question is: How do I convert string-ed regex into an actual regular expression?
UPDATE: It wasn't until Felix King kindly explained to me that
var array = ["/wolves/i", "/Duck/"];
can safely become:
var array = [/wolves/i, /Duck/];
Try this:
var regexSplit = regex.split( '/' );
var realRegex = new RegExp( regexSplit[1], regexSplit[2] );
Or better:
var regexMatch = regex.match( /^\/(.*)\/([^\/]*)$/ );
var realRegex = new RegExp( regexMatch[1], regexMatch[2] );
Better cause if your regex contains '/', the first one will fail. ;)
as stolen from here:
Use the RegExp object constructor to create a regular expression from a string:
var re = new RegExp("a|b", "i");
// same as
var re = /a|b/i;

Categories