Javascript Regex Issue - javascript

I'm trying to build a regex to test if the referrer contains a certain url (but includes query parameters etc)
Apologies if it's bad but it's my first attempt:
(ftp|http|https):\/\/urlhere\.com\/directoryhere(\?|/[^-+(a-zA-Z)]|$)
It works perfectly on here:
http://gskinner.com/RegExr/
But when I try it in in JavaScript/Firebug using:
document.referrer.match(/(ftp|http|https):\/\/urlhere\.com\/directoryhere(\?|/[^-+(a-zA-Z)]|$)/gi);
I get the error:
SyntaxError: unterminated parenthetical
Any help appreciated.

There is a / which is unescaped after directoryhere - (\?|/[
(ftp|http|https):\/\/urlhere\.com\/directoryhere(\?|\/[^-+(a-zA-Z)]|$)

You have missed escape one / before [^-+(a-zA-Z)]
Try
document.referrer.match(/(ftp|http|https):\/\/urlhere\.com\/directoryhere(\?|\/[^-+(a-zA-Z)]|$)/gi);

Related

Using JavaScript Regex to replace some content I get a Unmatched ')' Regex error

I'm moving a large blog from WordPress to another platform, and I am trying to re-create WordPress shortcodes with Javascript.
I've been able to write the Regex to replace [youtube]'s shortcodes without problems, but I'm having problems with [soundcloud]'s.
The format of the shortcode is the following:
[soundcloud url=”http://api.soundcloud.com/tracks/33660734”]
I created the following Regex rule, that seems to work on Regex 101
\[soundcloud url="http(s?):\/\/api\.soundcloud\.com\/tracks\/([a-zA-Z0-9]*)"(\s*?)\]
https://regex101.com/r/JKL45q/2
But when I include it in my script:
{
service: 'soundcloud',
regex: new RegExp('\[soundcloud url="http(s?):\/\/api\.soundcloud\.com\/tracks\/([a-zA-Z0-9]*)"(\s*?)\]', 'ig'),
},
I get this error, which I can't understand:
main.js:29 Uncaught SyntaxError: Invalid regular expression: /[soundcloud url="http(s?)://api.soundcloud.com/tracks/([a-zA-Z0-9]*)"(s*?)]/: Unmatched ')' (at main.js:29:14)
at new RegExp (<anonymous>)
at main.js:29:14
at main.js:142:3
The source script is here:
https://hotmc.pages.dev/assets/js/main.js
This is a page where the error occurs in the console:
https://hotmc.pages.dev/2011/01/10/esclusivo-anteprima-album-micha-soul-un-brano-in-free-download
Can anyone help? I found other questions about this error, but haven't been able to apply the suggested fixes.
Thank you in advance,
S.
I think you can remove the () of the ([a-zA-Z0-9]*)
new RegExp('[soundcloud url="http(s?):\/\/api\.soundcloud\.com\/tracks\/[a-zA-Z0-9]*"(\s*?)]', 'ig').test(`[soundcloud url="http://api.soundcloud.com/tracks/33660734"]`)
I have been able to get rid of the error by changing hot the RegExp object is initialized.
From this:
new RegExp('\[soundcloud url="http(s?):\/\/api\.soundcloud\.com\/tracks\/([a-zA-Z0-9]*)"(\s*?)\]', 'ig')
To this:
new RegExp(/\[soundcloud url="http(s?):\/\/api\.soundcloud\.com\/tracks\/([a-zA-Z0-9]*)"(\s*?)\]/, 'ig')

Regex returns nothing to repeat [duplicate]

I'm new to Regex and I'm trying to work it into one of my new projects to see if I can learn it and add it to my repitoire of skills. However, I'm hitting a roadblock here.
I'm trying to see if the user's input has illegal characters in it by using the .search function as so:
if (name.search("[\[\]\?\*\+\|\{\}\\\(\)\#\.\n\r]") != -1) {
...
}
However, when I try to execute the function this line is contained it, it throws the following error for that specific line:
Uncaught SyntaxError: Invalid regular expression: /[[]?*+|{}\()#.
]/: Nothing to repeat
I can't for the life of me see what's wrong with my code. Can anyone point me in the right direction?
You need to double the backslashes used to escape the regular expression special characters. However, as #Bohemian points out, most of those backslashes aren't needed. Unfortunately, his answer suffers from the same problem as yours. What you actually want is:
The backslash is being interpreted by the code that reads the string, rather than passed to the regular expression parser. You want:
"[\\[\\]?*+|{}\\\\()#.\n\r]"
Note the quadrupled backslash. That is definitely needed. The string passed to the regular expression compiler is then identical to #Bohemian's string, and works correctly.
Building off of #Bohemian, I think the easiest approach would be to just use a regex literal, e.g.:
if (name.search(/[\[\]?*+|{}\\()#.\n\r]/) != -1) {
// ... stuff ...
}
Regex literals are nice because you don't have to escape the escape character, and some IDE's will highlight invalid regex (very helpful for me as I constantly screw them up).
For Google travelers: this stupidly unhelpful error message is also presented when you make a typo and double up the + regex operator:
Okay:
\w+
Not okay:
\w++
Firstly, in a character class [...] most characters don't need escaping - they are just literals.
So, your regex should be:
"[\[\]?*+|{}\\()#.\n\r]"
This compiles for me.
Well, in my case I had to test a Phone Number with the help of regex, and I was getting the same error,
Invalid regular expression: /+923[0-9]{2}-(?!1234567)(?!1111111)(?!7654321)[0-9]{7}/: Nothing to repeat'
So, what was the error in my case was that + operator after the / in the start of the regex. So enclosing the + operator with square brackets [+], and again sending the request, worked like a charm.
Following will work:
/[+]923[0-9]{2}-(?!1234567)(?!1111111)(?!7654321)[0-9]{7}/
This answer may be helpful for those, who got the same type of error, but their chances of getting the error from this point of view, as mine! Cheers :)
for example I faced this in express node.js when trying to create route for paths not starting with /internal
app.get(`\/(?!internal).*`, (req, res)=>{
and after long trying it just worked when passing it as a RegExp Object using new RegExp()
app.get(new RegExp("\/(?!internal).*"), (req, res)=>{
this may help if you are getting this common issue in routing
This can also happen if you begin a regex with ?.
? may function as a quantifier -- so ? may expect something else to come before it, thus the "nothing to repeat" error. Nothing preceded it in the regex string so it didn't get to quantify anything; there was nothing to repeat / nothing to quantify.
? also has another role -- if the ? is preceded by ( it may indicate the beginning of a lookaround assertion or some other special construct. See example below.
If one forgets to write the () parentheses around the following lookbehind assertion ?<=x, this will cause the OP's error:
Incorrect: const xThenFive = /?<=x5/;
Correct:
const xThenFive = /(?<=x)5/;
This /(?<=x)5/ is a positive lookbehind: we're looking for a 5 that is preceded by an x e.g. it would match the 5 in x563 but not the 5 in x652.

javascript regex invalid quantifier error

I have the following javascript code:
if (url.match(/?rows.*?(?=\&)|.*/g)){
urlset= url.replace(/?rows.*?(?=\&)|.*/g,"rows="+document.getElementById('rowcount').value);
}else{
urlset= url+"&rows="+document.getElementById('rowcount').value;
}
I get the error invalid quantifier at the /?rows.*?.... This same regex works when testing it on http://www.pagecolumn.com/tool/regtest.htm using the test string
?srt=acc_pay&showfileCL=yes&shownotaryCL=yes&showclientCL=no&showborrowerCL=yes&shownotaryStatusCL=yes&showclientStatusCL=yes&showbillCL=yes&showfeeCL=yes&showtotalCL=yes&dir=asc&closingDate=12/01/2011&closingDate2=12/31/2011&sort=notaryname&pageno=0&rows=anything&Start=0','bodytable','xyz')
In this string, the above regex is supposed to match:
rows=anything
I actually don't even need the /? to get it to work, but if I don't put that into my javascript, it acts like it's not even regex... I'm terrible with Regex period, so this one has me pretty confused. And that error is the only one I am getting in Firefox's error console.
EDIT
Using that link I posted above, it seems that the leading / tries to match an actual forward slash instead of just marking the code as the beginning of a regex statement. So the ? is in there so that if it doesn't match the / to anything, it continues anyway.
RESOLUTION
Ok, so in the end, I had to change my regex to this:
/rows=.*(?=\&?)/g
This matched the word "rows=" followed by anything until it hit an ampersand or ran out of text.
You need to escape the first ?, since it has special meaning in a regex.
/\?rows.*?(?=\&)|.*/g
// ^---escaped
regtest.htm produces
new RegExp("?rows.?(?=\&)|.", "") returned a SyntaxError: invalid
quantifier
The value you put into the web site shouldn't have the / delimiters on the regex, so put in ?rows.*?(?=\&)|.* and it shows the same problem. Your JavaScript code should look like
re = /rows.*?(?=\&)|.*/g;
or similar (but that is a pointless regex as it matches everything). If you can't fix it, please describe what you want to match and show your JavaScript
You might consider refactoring you code to look something like this:
var url = "sort=notaryname&pageno=0&rows=anything&Start=0"
var rowCount = "foobar";
if (/[\?\&]rows=/.test(url))
{
url = url.replace(/([\?\&]rows=)[^\&]+/g,"$1"+rowCount);
}
console.log(url);
Output
sort=notaryname&pageno=0&rows=foobar&Start=0

URL regex does not work in javascript

I am trying to use John Gruber's URL regex in Javascript but NetBeans keeps telling me there is a syntax error and illegal errors:
var patt = "/(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])
|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]
{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|
(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|
(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:
'".,<>?«»“”‘’]))/";
Anyone know how to solve this?
As others have said, it's the double quote. But alternatively, you can just write the regexp as a literal in javascript (but then you need to escape the forward slashes in lines 1 and 3 instead).
var regexp = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i;
I also moved the case-insensitive modifier to the end. Just because. (edit: Well, not just "because" - see Alan Moore's comment below)
Note: Whether you use a literal or a string, it has to be on 1 line.
put the whole expression in one line, and remove the quotes at the start and end so it looks like this var patt = /the-long-patttern/;, netbeans will still complain, but the browsers won't and thats what matters.
You should write it like this in NetBeans:
"(?i)\\b((?:[a-z][\\w-]+:(?:\\/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]"
+ "+[.][a-z]{2,4}\\/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))"
+ "+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))";

javascript plain text url parsing

I'm trying to search plain old strings for urls that begin with http, but all the regex I find doesn't seem to work in javascript nor can I seem to find an example of this in javascript.
This is the one I'm trying to use from here and here:
var test = /\b(?:(?:https?|ftp|file)://www\.|ftp\.)[-A-Z0-9+&##/%=~_|$?!:,.]*[A-Z0-9+&##/%=~_|$]/;
But when I try to run it, I get "Unexpected token |" errors.
Ok, a comment seems to be not enough, hard to find full answer. I rewrite whole proper regexp: (tested, it works good)
var test = /\b(?:(?:https?|ftp|file):\/\/www\.|ftp\.)[-A-Z0-9+&##\/%=~_|$?!:,.]*[A-Z0-9+&##\/%=~_|$]/i;
The i on the end means 'ignore case', so it is necessary for this regexp.
You're using / as your regex delimiter, and are also using / within the regex (before www), so the regex actually terminates after the first / before www. Change it to:
var test = /\b(?:(?:https?|ftp|file):\/\/www\.|ftp\.)[-A-Z0-9+&##/%=~_|$?!:,.]*[A-Z0-9+&##/%=~_|$]/;
^^^^ escape here

Categories

Resources