我有一个字符串,其值为
"Your <span data-schedule="departureAirportCode"></span> <span class="icon icon> </span> <span class="alt">to</span>"
我需要根据开始和结束span标签对它们进行拆分,并且最终输出应该是
var newArray=[<span data-schedule="departureAirportCode"></span>,<span class="icon icon> </span>,span class="alt">to</span>]
任何帮助都将非常有帮助,在此先感谢
答案 0 :(得分:0)
首先,您必须纠正字符串中的某些错字:
'
而不是"
封装字符串,或者转义"
,或者使用template literal "
中的<span class="icon icon
(注意:为什么同一堂课要两次?)获得有效的HTML字符串后,将其扔到容器中将使您可以轻松地进行操作和解析。获取跨度并使用jQuery .toArray()
将返回您期望的输出。
var str = 'Your <span data-schedule="departureAirportCode"></span> <span class="icon"> </span> <span class="alt">to</span>'
var arr = $("<div />") //Create a container for the HTML string
.html(str) //Populate it with the HTML
.children("span") //Find the <span> elements
.toArray(); //Return them as an array
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>