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

javascript - Replacing white spaces to commas - Stack Overflow

programmeradmin4浏览0评论

Well, i'm using regex to replace all white spaces to mas but there's a white space at the end and i don't know how to make the regex not replace him

What I have

25DEL 38DEL A73G

JS

 var valor = $("#mapaArquivos option:selected").val().replace(/\s+/g, ", ");

Output

25DEL, 38DEL, A73G,

Right Output

25DEL, 38DEL, A73G

Thanks for the help anyway!

Well, i'm using regex to replace all white spaces to mas but there's a white space at the end and i don't know how to make the regex not replace him

What I have

25DEL 38DEL A73G

JS

 var valor = $("#mapaArquivos option:selected").val().replace(/\s+/g, ", ");

Output

25DEL, 38DEL, A73G,

Right Output

25DEL, 38DEL, A73G

Thanks for the help anyway!

Share Improve this question asked Feb 9, 2013 at 4:46 Bruno AndradeBruno Andrade 2613 gold badges8 silver badges17 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

Trim the value before applying regex. this way there will be no trailing or leading spaces

var valor = jQuery.trim($("#mapaArquivos option:selected").val())
                  .replace(/\s+/g, ", ");

You could trim the end or you could use

replace( /(?!\s+$)\s+/g, ", " );

A negative look-ahead prevents trailing spaces being replaced.

This should do (it trims the Whitespaces of the initial value first)

var valor = $("#mapaArquivos option:selected").val().replace(/^\s+|\s+$/g,"").replace(/\s+/g, ", ");

if not, you might want to try replace(/\s+$/,"")instead (trims only at the end

发布评论

评论列表(0)

  1. 暂无评论