开发者

Javascript replace hypens with space

开发者 https://www.devze.com 2023-03-10 03:15 出处:网络
I am getting this value from DatePicker var datepickr = \'Jun-29-20开发者_如何学运维11\'; I want to replace underscores(-) with space .

I am getting this value from DatePicker

var datepickr = 'Jun-29-20开发者_如何学运维11';

I want to replace underscores(-) with space .

I tried this way , but it isn't working

var b = datepickr.replace("-",' ');


Just for reference:

var datepickr = 'Jun-29-2011';
datepickr.replace("-",  " ");  // returns "Jun 29-2011"
datepickr.replace(/-/,  " ");  // returns "Jun 29-2011"
datepickr.replace(/-/g, " ");  // returns "Jun 29 2011" (yay!)

The difference is the global modifier /g, which causes replace to search for all instances. Note also that - must be escaped as \- when it could also be used to denote a range. For example, /[a-z]/g would match all lower-case letters, whereas /[a\-z]/g would match all a's, z's and dashes. In this case it's unambiguous, but it's worth noting.

EDIT

Just so you know, you can do it in one line without regex, it's just impressively unreadable:

while (str !== (str = str.replace("-", " "))) { }


.replace is supposed to take a regular expression:

var b = datepickr.replace(/-/g,' ');

I'll leave it as an exercise to the reader to research regular expressions to the full.

(The important bit here, though, is the flag /gglobal search)


Try this:

var datepickr = 'Jun-29-2011';
var b = datepickr.replace( /-/g, ' ' );

The /g causes it to replace every -, not just the first one.


var b = 'Jun-29-2011'.replace(/-/g, ' ');

Or:

var b = 'Jun-29-2011'.split('-').join(' ');


replace works with regular expressions, like so:

> "Hello-World-Hi".replace(/-/g, " ")
Hello World Hi


try:

var b = datepickr.toString().replace("-",' ');

I suspect that you are trying to replace chars inside a Date object.

0

精彩评论

暂无评论...
验证码 换一张
取 消