javascript - 将字符串拆分为数组

标签 javascript jquery html tokenize

我在表单中有一个字符串,

var k= '<html><div id="test">it is interesting</div></html>' ,

我正在尝试将其转换为形式数组

<html>
<div id="test">
it
is
interesting
</div>
</html>

我正在使用 Javascript 来执行此任务。我可以使用拆分函数检测单词之间的空格来拆分字符串,但我该如何拆分 HTML 标记。

最佳答案

var k='<html><div id="test">it is interesting</div></html>';
var a=k.match(/(<.+?>)|([^ ]+?(?=[ <]))/g);
console.log(a); // ["<html>", "<div id="test">", "it", "is", "interesting", "</div>", "</html>"]

更新:如果您的字符串可以包含子字符串 "<>" (在 HTML 中无效)然后尝试使用正则表达式并稍作更改:/(<.*?>)|([^ ]+?(?=[ <]))/g

更新:如果你需要解释\n\r\t符号(换行符、回车符、制表符)作为空格尝试使用下一个正则表达式:/(<.*?>)|(\S+?(?=[\s<]))/g (另请参阅上述更新中关于用法的备注 *+ )

var k,a,rg=/(<.*?>)|(\S+?(?=[\s<]))/g;

k='<html><div id="test"> it is interesting</div></html>';
a=k.match(rg);
console.log(a); // ["<html>", "<div id="test">", "it", "is", "interesting", "</div>", "</html>"]

k='<div class=\"Normal\" algoscore=\"338\">\n <p><img src=\"/getBinaryFile.php?Id=69\" /></p>\n';
a=k.match(rg);
console.log(a); // ["<div class="Normal" algoscore="338">", "<p>", "<img c="/getBinaryFile.php?Id=69" />", "</p>"]

关于javascript - 将字符串拆分为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11839715/

相关文章:

javascript - 循环中的 Handlebars 装饰器

Jquery on click 函数将类添加到特定 div

javascript - 为什么 anchor 不能仅在 Firefox 中使用 map 坐标?

html - 从 mod_autoindex 中删除最后修改时间和大小

javascript - 从 Javascript 和 HTML 运行 Unix 命令

javascript - 当站点不是其 URL 的根时,如何在 getJSON 调用中定位 API

javascript - 异步回调内部调试

javascript - 使用 jQuery 从 URL 获取 JSON

javascript - 无法使用 .tmpl onchange 调用 reg.cgi 中的 JS 函数

java - 用 Java 解析简单的 HTML