我有一个由“br”和“nbsp;”组成的字符串标签,我需要的是我需要将字符限制为 100,这意味着只应显示 100 个字符,因为每个“br”需要 4 个字符而不是 100 个字符,我得到 108,要低于输出我可以这样做单行
data.substr(0,100)
输出=>
it to make a type specimen book.
It has survived not only five centuries, but also the leap
但它包含 br 标签,我不想删除 br 和 nbsp;但不要算这个
预期输出=>
it to make a type specimen book.
It has survived not only five centuries, but also the leap into ele
我已经做了一些片段,但它给出的计数是 108
var data = `it to make a type specimen book. <br><br>It has survived not only five centuries, but also the leap into electronic typesetting, <br><br>remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages<br><br>, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.`
// removes nbsp
var docDesc = data.replace(/[&]nbsp[;]/gi," ");
// removes br
var stringData = docDesc.replace(/[<]br[^>]*[>]/gi,"");
var subData = stringData.substr(0,100)
function test(subData) {
var n = subData.split(" ");
return n.slice(Math.max(n.length - 5, 1))
}
var lastData = test(subData);
var lastString = lastData.join(" ")
var finalData = data.substring(0,data.indexOf(lastString)) + lastString
console.log(finalData)
console.log(finalData.length)
最佳答案
在最简单的形式中,您可以编写一个类似于子字符串但排除一些“单词”的函数,如下所示:
function substringWithExcludes(str, excludes, length) {
let idx = 0;
let len = 0;
while(idx < str.length && len < length){
let match = false;
for(let exclude of excludes) {
if(str.startsWith(exclude, idx)) {
idx += exclude.length;
match = true;
break;
}
}
if(!match) {
len++;
idx++;
}
}
return str.substring(0, idx);
}
这被称为:
const data = `it to make a type specimen book. <br>\r\n<br>\r\nIt has survived not only five centuries, but also the leap into electronic typesetting, <br>\r\n<br>\r\nremaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages<br>\r\n<br>\r\n, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.`;
const result = substringWithExcludes(data, ["\r", "\n", " ", "<br>"], 100);
len
跟踪没有 <br>
的字符串长度所有这一切,同时 idx
包括这些比赛。对于每个排除,我们需要做的是首先查看它是否匹配,以及是否将长度添加到 idx
。如果不匹配,则需要包含一个有效字符(同时增加 len
和 idx
)。
对于大型 length
可能会很慢还有很多excludes
,但它完成了工作。您可以添加不区分大小写的特定情况,并且 <br />
必要时进行匹配。 startsWith
需要时可以与正则表达式匹配交换。
关于javascript - 不要将 br 和 nbsp 计入字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50462227/