1

如何在javascript中编写一个脚本来检查"Line1\nLine2\nLine3..."字符串中的所有行(),如果有重复的行,那么只留下一个并忽略br标签?

var s = "Hello world\n<BR>\nThis is some text\nThis is some text\n<BR>\nThis is some text"
line1 = "Hello world"
line2 = "<BR>"
line3 = "This is some text"
line4 = "This is some text"
line5 = "<BR>"
line6 = "This is some text"

var result = "Hello world\n<BR>\nThis is some text\n<BR>"
line 1 = "Hello world"
line 2 = "<BR>"
line 3 = "This is some text"
line 4 = "<BR>"
4

3 回答 3

2

我认为最短的解决方案是这个。

myStr
.split("\n")
.filter((item, i, allItems) => {
  return i === allItems.indexOf(item);
})
.join("\n");
于 2019-08-16T08:45:51.263 回答
1
var pieces = s.split("\n"); //This will split your string
var output = []; //Output array

for (var i = 0; i < pieces.length; i++) { //Iterate over input...

   if (pieces[i] == '<BR>' || output.indexOf(pieces[i]) < 0) { //If it is <BR> or not in output, add to output
      output.push(pieces[i]);
   }

}

var newS = output.join("\n"); //Concatenates the string back, you don't have to do this if you want your lines in the array

这里我们有 jsFiddle:http: //jsfiddle.net/7s88t/

据您所知,该indexOf函数返回pieces[i]输出数组的位置。如果未找到,则返回-1。这就是为什么我检查它是否小于零。

希望我有所帮助。

编辑

根据您的要求,采用小写:

if (pieces[i].toLowerCase() == '<br>' || pieces[i].toLowerCase() == '<br/>' || pieces[i].toLowerCase() == '<br />' || output.indexOf(pieces[i]) < 0) {
于 2013-06-06T23:33:58.490 回答
0

1)通过换行符将您的文本分成一个数组:

var arr = s.split("\n");

2)删除所有重复条目:

var str;
for(var i=0; i<arr.length; i++) {
    str = arr[i];
    //Takes into account all bad forms of BR tags. Note that in your code you are using
    //invalid br tags- they need to be <br /> (self-closing)
    if(inArray(str, arr) && str != "<br>" && str != "<br/>" && str != "<br />"){
        arr.splice(i, 1);
    }
};

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle) return true;
    }
    return false;
}

3)让它们重新变成一个字符串

//Note joining with newline characters will preserve your line outputs :)
var output = arr.join("\n"); 

这种方法很好,因为它避免使用正则表达式,甚至不需要考虑<br />标签,并且使用原生 JS,这意味着你可以将它放在任何你想要的地方。我没有测试这段代码,我只是把它写出来,所以它可能包含错误。但这应该是一个很好的起点。干杯!

于 2013-06-06T23:37:56.527 回答