Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Using $ to match end-of-input gives a zero-length match everywhere else but no evidence of a match with WebKit:

function showBug() {
  Result = "the end.".replace( /(end\.)([\s]|$)?/img, makeChange );
  return;
  }
function makeChange() {
  for ( var i = 0; i < arguments.length; i += 1 ) {
    document.write( "arg" + i + " -->" + arguments[ i ] + "<--"  + "<BR>" );
    }
  }               

gives

arg0 -->end.<--
arg1 -->end.<--
arg2 -->undefined<--
arg3 -->4<--
arg4 -->the end.<--

for AppleWebKit/534.55.3 (KHTML, like Gecko) Version/5.1.5 Safari/534.55.3, also for AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19.

Opera (Presto/2.10.229 Version/11.62), FF (Gecko/20100101 Firefox/10.0.2) and IE (MSIE 8.0; Trident/4.0) all give

arg0 -->end.<--
arg1 -->end.<--
arg2 --><--
arg3 -->4<--
arg4 -->the end.<--

which means I can detect the match in $2 (it's actually about interpreting a trailing dot on a url as not being part of the url). I'm currently adding a trailing space for WebKit, and taking it off afterwards, but I'm wondering if anyone has a better solution and can confirm I should raise this as a bug.

share|improve this question
What happens if you remove the "?" from the regular expression? – John Fisher Apr 27 '12 at 17:11
2  
First, you don't need the | in that expression. So you could write it /(end\.)([\s])?$/ to match something before end-of-line. Second, are you trying to match 0 or 1 of 's' and '\' or are you trying to match whitespace \s (no brackets)? jsfiddle.net/2hZdT – Mathletics Apr 27 '12 at 17:13
I just tested here in Chrome and it works. – Rodrigo Manguinho Apr 27 '12 at 17:15
var t = "the end.".replace( /(end\.)([\s]|$)+/img, "###"); the value of "t" is "the ###" – Rodrigo Manguinho Apr 27 '12 at 17:16
@JohnFisher Good idea, that makes WebKit show a match occurred. But now the regex doesn't do what I want i.e. find a dot with at least one space after else eoi. – anweald Apr 27 '12 at 17:23
show 8 more comments

1 Answer

If you want to match the empty string, you should include the question mark inside the capturing group, e.g.

/(end\.)((?:\s|$)?)/

The reason is that a group that does not capture anything is not the same thing that a group that captures an empty string. For example, think at what the second parentheses should capture in the following example :

/a(b(x))?c/.exec('ac');   
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.