سؤال

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.

هل كانت مفيدة؟

المحلول

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 need to escape the first ?, since it has special meaning in a regex.

   /\?rows.*?(?=\&)|.*/g
//   ^---escaped

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top