Match returning null in JavaScript - 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));

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)

Convert URL to string and extract part of to it to a variable [duplicate]

I have this code, it looks alright and is really basic, but i can't make it work:
function checkValid(elem){
var abc = elem.value;
var re = "/[0-9]/";
var match = re.test(abc);
alert(match);
}
It matches 0 and 9, but not 1 to 8, what's wrong here? Thanks.
re is a string, not a RegExp object.
You need to use a regex literal instead of a string literal, like this:
var re = /[0-9]/;
Also, this will return true for any string that contains a number anywhere in the string.
You probably want to change it to
var re = /^[0-9]+$/;
Try removing the double quotes...
var re = /[0-9]/;
Use \d to match a number and make it a regular expresison, not a string:
var abc = elem.value;
var re = /\d/;
var match = re.test(abc);
alert(match);

How to extract string in regex

I have string in this format:
var a="input_[2][invoiceNO]";
I want to extract "invoiceNo" string. I've tried:
var a="input_[2][invoiceNO]";
var patt = new RegExp('\[(.*?)\]');
var res = patt.exec(a);
However, I get the following output:
Array [ "[2]", "2" ]
I want to extract only invoiceNo from the string.
Note: Input start can be any string and in place of number 2 it can be any number.
I would check if the [...] before the necessary [InvoiceNo] contains digits and is preceded with _ with this regex:
/_\[\d+\]\s*\[([^\]]+)\]/g
Explanation:
_ - Match underscore
\[\d+\] - Match [1234]-like substring
\s* - Optional spaces
\[([^\]]+)\] - The [some_invoice_123]-like substring
You can even use this regex to find invoice numbers inside larger texts.
The value is in capture group 1 (see m[1] below).
Sample code:
var re = /_\[\d+\]\s*\[([^\]]+)\]/g;
var str = 'input_[2][invoiceNO]';
while ((m = re.exec(str)) !== null) {
alert(m[1]);
}
You can use this regex:
/\[(\w{2,})\]/
and grab captured group #1 from resulting array of String.match function.
var str = 'input_[2][invoiceNO]'
var m = str.match(/\[(\w{2,})\]/);
//=> ["[invoiceNO]", "invoiceNO"]
PS: You can also use negative lookahead to grab same string:
var m = str.match(/\[(\w+)\](?!\[)/);
var a="input_[2][invoiceNO]";
var patt = new RegExp('\[(.*?)\]$');
var res = patt.exec(a);
Try this:
var a="input_[2][invoiceNO]";
var patt = new RegExp(/\]\[(.*)\]/);
var res = patt.exec(a)[1];
console.log(res);
Output:
invoiceNO
You could use something like so: \[([^[]+)\]$. This will extract the content within the last set of brackets. Example available here.
Use the greediness of .*
var a="input_[2][invoiceNO]";
var patt = new RegExp('.*\[(.*?)\]');
var res = patt.exec(a);

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

regular expression not working properly

I have problem with JavaScript Regular Expression. I have test it on this website and it's working fine - http://www.pagecolumn.com/tool/regtest.htm .
var str = "Stalowa Wola;Nisko;Rzeszow";
var re = new RegExp("Stalowa Wola[a-zA-Z\W]*Rzeszow", "i");
var myArray = str.match(re);
console.log(myArray);
But when I trying to run this code on my website, it's not working.Console return 'null' and I don't know why. I noticed that when i remove 'Rzeszow' from RegExp it's starts working.
var str = "Stalowa Wola;Nisko;Rzeszow";
var re = new RegExp("Stalowa Wola[a-zA-Z\\W]*Rzeszow", "i");
var myArray = str.match(re);
console.log(myArray);
You need to escape the backslash.
Alternatively use this notation:
var str = "Stalowa Wola;Nisko;Rzeszow";
var re = /Stalowa Wola[a-zA-Z\W]*Rzeszow/i;
var myArray = str.match(re);
console.log(myArray);
The downside is that you must know the structure of the regex before runtime.
http://www.regular-expressions.info/javascript.html

Categories