admin管理员组文章数量:1389897
I have a multiple select
box on my page. I can get the values of all the selected child option
s 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 option
s 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
6 Answers
Reset to default 4var 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;
}
本文标签: javascriptConvert array to spacedelimited stringwhile joining individual valuesStack Overflow
版权声明:本文标题:javascript - Convert array to space-delimited string, while joining individual values - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744632724a2616638.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论