Why doesn't this simple javascript replacement change the slash to a slash?

I have this HTML element:

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

And I bind the click event to .date, so when it clicks, the function is called. My goal is to ultimately indicate the date (from the identifier) ​​using a slash instead of a dash:

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

It may not be much simpler ... but the result that displays with a warning () still has a dash, "4-12-2012" ... which is quite obvious that I am missing here?! :-)

+4
source share
4 answers

The answer to your question has already been published, but on the side of the note, I see no reason to use jquery in this situation. All he does is call unnecessary functions

try it

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

here is a good test recommendation:

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

edit: forgot to delete ticks

+6
source

try the following:

remove ' around regex

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

A simple regexp as seen on this jsfiddle :

 d = $(this).attr('id').replace(/-/g, '/') 
+2
source

Do not put the regular expression in quotation marks:

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

Source: https://habr.com/ru/post/1400048/


All Articles