如何将A Div的文本(字符串)转换为数组

时间:2018-01-12 19:15:07

标签: javascript jquery

您能看一下这个演示,让我知道如何将div的文本转换为数组吗?

console.log($("#colors").Text().toArray());
console.log($.makeArray($("#colors").Text()));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <div id="colors">
                Pink
                LightPink
                HotPink
                DeepPink
                PaleVioletRed
                MediumVioletRed
                LightSalmon
                Salmon
                DarkSalmon
                LightCoral
                IndianRed
                Crimson
                FireBrick
                DarkRed
                Red
    </div>

4 个答案:

答案 0 :(得分:2)

一步一步:

console.log($("#colors").text());
console.log($("#colors").text().replace(/ +/g, ""));
console.log($("#colors").text().replace(/ +/g, "").replace(/^\n|\n$/g, ""));
console.log($("#colors").text().replace(/ +/g, "").replace(/^\n|\n$/g, "").split("\n"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="colors">
  Pink
  LightPink
  HotPink
</div>

答案 1 :(得分:2)

根据您当前的标记,您可以尝试以下方式:

var obj = $("#colors").text().trim();
var arr = obj.split("\n");

for(var i = 0; i < arr.length; i++){ // This loop for remove white space.
 arr[i] = arr[i].trim();
}

console.log(arr);

答案 2 :(得分:0)

您无法将文字转换为数组。 jQuery.makeArray()专门用于将类似jQuery数组的对象转换为本机数组。

你想要String.split()

答案 3 :(得分:0)

&#13;
&#13;
console.log($("#colors").text().trim().split(/\s+/));// split on white spaces
console.log($.trim($("#colors").text()).split(/\s+/));// for old browsers like IE
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <div id="colors">
                Pink
                LightPink
                HotPink
                DeepPink
                PaleVioletRed
                MediumVioletRed
                LightSalmon
                Salmon
                DarkSalmon
                LightCoral
                IndianRed
                Crimson
                FireBrick
                DarkRed
                Red
    </div>
&#13;
&#13;
&#13;