Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this simple javascript replace change the dash to slash?

I have this HTML element:

<div id='4-12-2012' class='date'>blah blah blah</div>

And I'm binding a click event to .date, so when it's clicked, a function is called. My goal is to end up with the date (from the ID) with slashes instead of dashes:

d = $(this).attr('id').replace('/-/g', '/');
alert(d);

This can't be much more straightforward... but the result that is displayed with the alert() still has dashes, "4-12-2012"... what totally obvious thing am I missing here?! :-)

like image 371
Eric Avatar asked Mar 06 '12 16:03

Eric


3 Answers

The answer to your question has already been posted, but on a side note, I see no reason to use jquery in this situation. All it is doing is calling un-needed functions

try this

d = this.id.replace(/-/g, '/');

here is a good reference with testing:

http://jsperf.com/el-attr-id-vs-el-id/7

edit: forgot to remove the ticks

like image 113
Johnny Craig Avatar answered Sep 28 '22 20:09

Johnny Craig


try this :

remove the ' around the regex

d = $(this).attr('id').replace(/-/g, '/');
like image 27
Royi Namir Avatar answered Sep 28 '22 18:09

Royi Namir


Simple regexp, as seen on this jsfiddle:

d = $(this).attr('id').replace(/-/g, '/')
like image 36
Konerak Avatar answered Sep 28 '22 20:09

Konerak