最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Why doesn't this simple javascript replace change the dash to slash? - Stack Overflow

programmeradmin2浏览0评论

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?! :-)

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?! :-)

Share Improve this question edited Mar 6, 2012 at 16:31 j08691 208k32 gold badges267 silver badges280 bronze badges asked Mar 6, 2012 at 16:30 EricEric 5,21510 gold badges44 silver badges74 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 11

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

try this :

remove the ' around the regex

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

Simple regexp, as seen on this jsfiddle:

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

Don't put the regex in quotes:

d = $(this).attr('id').replace(/-/g, '/');
发布评论

评论列表(0)

  1. 暂无评论