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

javascript - Convert array to space-delimited string, while joining individual values - Stack Overflow

programmeradmin1浏览0评论

I have a multiple select box on my page. I can get the values of all the selected child options in jQuery easily like this:

$("#select").val();

That gives me an array like this:

["Hello", "Test", "Multiple Words"]

Now, I want to convert this array into a space-delimited string, but also join the individual words in each value with a dash, so that I end up with this:

"Hello Test Multiple-Words"

How would I go about doing that?

I have a multiple select box on my page. I can get the values of all the selected child options in jQuery easily like this:

$("#select").val();

That gives me an array like this:

["Hello", "Test", "Multiple Words"]

Now, I want to convert this array into a space-delimited string, but also join the individual words in each value with a dash, so that I end up with this:

"Hello Test Multiple-Words"

How would I go about doing that?

Share Improve this question asked Jan 30, 2013 at 20:59 daGUYdaGUY 28.8k29 gold badges77 silver badges123 bronze badges 1
  • 1 whathaveyoutried. – Jay Blanchard Commented Jan 30, 2013 at 21:02
Add a ment  | 

6 Answers 6

Reset to default 4
var values = $("#select").val();

for (var i = 0; i < values.length; ++i) {
    values[i] = values[i].replace(" ", "-");
}

var spaceDelimitedString = values.join(" ");
var result = $.map($("#select").val() || [], function (x) {
    return x.replace(/\s/g, '-');
}).join(' ');

If Multiple-Words can be as Multiple Words, then you can simply use .join and get the final output as "Hello Test Multiple Words".

If not, you can write a loop like below to get the result.

var myList = ["Hello", "Test", "Multiple Words"];
var result = '';
for (var i = 0; i < myList.length; i++) {
   result += myList[i].replace(/\s/g, '-') + ' ';
}

DEMO: http://jsfiddle/bmXk5/

Here a simple one liner with Array.map:

var arr = ["Hello", "Test", "Multiple Words"];
arr.map(function(val) { return val.replace(' ', '-') }).join(' ');
var vals = ["Hello", "Test", "Multiple Words"];
var result = $.map(vals, function(str){ return str.replace(/\s/g, '-') })
  .join(' ');

This should do the job for you.

function bineWords(arr) {
    var i, l;
    for(i = 0, l = arr.length; i < l; i++) {
        arr[i] = arr[i].replace(' ', '-') ;
    }
    return arr;
}
发布评论

评论列表(0)

  1. 暂无评论