0

I have a javascript function which looks for a string of certain format and then converts it into a link

<script>
var re = /Ticket-([0-9]*?(?=-)-[0-9]*)/; 
var str = 'ASD Ticket-492-367 - Make my day.'; 
t = str.replace(re,'<a href="http://myworld/ticket/$1">$0</a>')
document.write(t);
</script>

It looks for Ticket-[some numbers]-[somenumbers] and converts it into a link. Now when i run it seperately in JS editors online it works. But when I run it in my script and lok at the page it does convert the string into a list but prints out literal $0 on the page instead of its value. Is my Javascript correct or ist something else in my script that's probably cuasing the erraneous relsuts. As always, any help is appreciated.

Fizi
  • 1,749
  • 4
  • 29
  • 55

3 Answers3

5

Javascript uses $& as the placeholder for the entire match, not $0 $number is only used as the placeholder for capture groups in parentheses. See MDN.

var re = /Ticket-([0-9]*?(?=-)-[0-9]*)/; 
var str = 'ASD Ticket-492-367 - Make my day.'; 
t = str.replace(re,'<a href="http://myworld/ticket/$1">$&</a>')
document.getElementById('result').innerHTML = t;
<div id="result"></div>
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • But it works in the cas eof $1. Why? How do you differentiate between matched groups – Fizi Apr 03 '15 at 21:19
  • 1
    `$number` is for capture groups in parentheses. `$&` is for the match of the whole regexp. – Barmar Apr 03 '15 at 21:21
  • just as a helpful note, http://regexr.com/ has a fantastic reference section on the left side of the page. If you go to Reference -> Substitution, it will give you the differences and examples between the operators in real time. – zfrisch Apr 03 '15 at 21:35
1

If you're matching a list you should use /g to make the regex global. $0 doesn't grab the matched value, $& does.

Here's a fiddle: http://jsfiddle.net/2p91co2g/

EDIT: Apparently jsfiddle is down or something. The HTML I used was:

<!DOCTYPE html>
<html>
<body>
Ticket-445-1235 - Make my day<br>
Ticket-445-1255 - Make his day<br>
Ticket-443-4356 - He's feeling lucky<br>
Ticket-443-5555 - punk<br>
</body>
</html>

And the javascript with the adjustments are:

window.onload = function() {
var re = /Ticket-([0-9]*?(?=-)-[0-9]*)/g; 
var str = document.body.innerHTML; 
t = str.replace(re,'<a href="http://myworld/ticket/$1">$&</a>')
document.write(t);
}
zfrisch
  • 8,474
  • 1
  • 22
  • 34
-2

Try escaping the dollar twice...

\\$