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

javascript - Regex to remove all whitescape except one between words? - Stack Overflow

programmeradmin1浏览0评论

Simple as the title, really.

Is there a Regex expression to remove all whitespace except one between words.

So

"  Hello. How   are  you     today?    "

would become

"Hello. How are you today?"

Simple as the title, really.

Is there a Regex expression to remove all whitespace except one between words.

So

"  Hello. How   are  you     today?    "

would become

"Hello. How are you today?"
Share Improve this question edited May 13, 2012 at 21:04 Alan Moore 75.2k13 gold badges107 silver badges160 bronze badges asked May 13, 2012 at 20:45 mythofechelonmythofechelon 3,78212 gold badges39 silver badges49 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 21

This will do what you wish:

"  Hello. How   are  you     today?    ".replace(/\s{2,}/g,' ').trim() 

fiddle: http://jsfiddle.net/REAdV/

As you may find that trim() may not work fro ie 6/7/8 and some older browsers versions I would suggest using .replace(/^\s+|\s+$/g,'')

var str = "    fsdf d34234sf    sdfsdf   "; 
str=str.replace(/^\s+|\s+$/g,'');
returns:fsdf d34234sf sdfsdf
发布评论

评论列表(0)

  1. 暂无评论