<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>拆分字符串,存入數組</title>
<style>
*{padding:0;margin:0;}
</style>
</head>
<body>
<h1 id="fruit">This is a list of items: cherries, limes, oranges, apples.</h1>
<div id="Flist"></div>
<script type="text/javascript">
var fruit=document.getElementById("fruit");
var content=fruit.lastChild.nodeValue;
//從HTML中獲得字符串,先要取得文本節點,取其nodeValue值,此處不能使用value,因爲不具value屬性。
var start=content.indexOf(":"),end=content.lastIndexOf(".");
var list=content.substring(start+1,end);
var Flist=list.split(",");
document.getElementById("Flist").innerHTML=Flist.join("||");
//用join()時,原數組不變,是新數組的連接符發生了改變。
</script>
</body>
</html>
若要刪除上述數組中各項的空格,有以下兩種方法:
1,正則表達式法:
var Flist=list.split(/\s*,\s*/g);//匹配空格,逗號,空格,*表示0-n次。然後刪掉它們。
2,trim()方法,注意trim只能刪掉字符串首尾的空格:
var Flist=list.split(",");
// 刪除數組中每一項的空格。
/*
Flist.forEach(function(item,index,array){
array[index]=item.trim();
});// trim()只能用來刪除字符串兩端的空格,因此只能對數組每一項進行遍歷刪除。*/