如何使用split()函数与HTML标签和空白

how to use split() function with html tag and whitespace

本文关键字:HTML 标签 空白 函数 何使用 split      更新时间:2023-09-26

我在字符串中使用split(" ")作为空白,使用split(/(<[^>]*>)/)作为html标记。

,但我必须一起使用。我想用空格和HTML标记来分割字符串,并将其放入数组中。我不想失去任何东西。字符串,HTML标签。

空格为's, html标签为split(/(<[^>]*>)/),我像这样使用new RegExp("'s+(<[^>]*>)", "g");

但是它不工作。

var htmlTagRegex = new RegExp("'s+(<[^>]*>)", "g");     
    var str = ""<div class="tab0">CSS code formatter</div><div class="tab2">CSS code compressor</div>";
    var myArray = str.split(htmlTagRegex);
    if(myArray != null){
        for ( i = 0; i < myArray.length; i++ ) { 
            var result = "myArray[" + i + "] = " + myArray[i]+"<br />";
            $(".tt-sns-clear").append(result);
        }           
    }   

不是100%确定你想做什么,但看起来空间需要是可选的,像's*而不是's+

例如:'s*(<[^>]*>)

既然你没有连接一个字符串到你的正则表达式更好的是:

var htmlTagRegex =/'s*(<[^>]*>)/g

输入字符串没有正确使用双引号,也没有编译,你需要混合使用单引号和双引号:

 '<div class="tab0">CSS code formatter</div><div class="tab2">CSS code compressor</div>';

所有的在一起看起来像

    var htmlTagRegex =/'s*(<[^>]*>)/g     
    var str = '<div class="tab0">CSS code formatter</div><div class="tab2">CSS code compressor</div>';
    var myArray = str.split(htmlTagRegex);
//outputs ["", "<div class="tab0">", "CSS code formatter", "</div>", "", "<div class="tab2">", "CSS code compressor", "</div>", ""]

字符串来自mysql。这就是html标签

和我曾经是这样的:var htmlTagRegex =/' s | (& lt; [^>] *>)/g;

但结果不是我想要的。

["","CSS","code","formatter","<div class="tab0"></div>","","CSS","code","compressor","<div class="tab1"></div>"]

我想要这样

["<div class="tab0">","CSS","code","formatter","","<div class="tab1">","CSS","code","compressor","</div>"]