0

我正在尝试将这样的 html 拆分为字符串:

<p class='class1'> Hello, this is my html </p>

我需要的是通过空格分割该html,忽略分割中的html标签,我目前得到这个结果:

["<p","class='class1'>","Hello,","this","is","my","html","</p>"]

但我需要它将标签视为一个完整的单词,以获得这个结果:

["<p class='class1'>","Hello,","this","is","my","html","</p>"]

我怎样才能得到这个结果?

编辑:

在 javascript 方面,我使用了一个简单的拆分:

var text = "<p class='class1'> Hello, this is my html </p>";
var splitText = text.split(' ');

在这种情况下 splitText 将是:

["<p","class='class1'>","Hello,","this","is","my","html","</p>"]

我尝试使用像 "/[<.*?>,\s]+/" 这样的正则表达式,但我的结果是:

var text = "<p class='class1'> Hello, this is my html </p>";
var splitText = text.split(/[<.*?>,\s]+/);

splitText = ["p class='class1'","Hello,","this","is","my","html","/p"]

提前致谢。

4

2 回答 2

1

我通过使用一个简单的正则表达式和 match 方法得到了这个。

var text = "<p class='class1'><p class='class2'>Hello world!</p></p>";
var splitText = text.match(/[\<].+?[\>]+|[^\s]+/g);

//splitText -> 
//["<p class='class1'>","<p class='class2'>","Hello","world!","</p>","</p>"]

感谢@MaveRick 的回答:)

于 2013-08-20T22:54:21.560 回答
1
var a = $("<p class='class1'>Hello, this is my html</p>");
var b = a.html().split(' ');
a.html('');
var c = a[0].outerHTML.split('><');
b.splice(0, 0,c[0]+'>');
b.splice(b.length+1, 0,'<'+c[1]);

b 将导致:["<p class="class1">", "Hello,", "this", "is", "my", "html", "</p>"]

注意:此代码仅适用于一维标签

于 2013-08-20T15:20:27.743 回答