我有一个“读更多”的角度指令,复制自:https://github.com/doukasd/AngularJS-Components/blob/master/dd-text-collapse/dd-text-collapse.js
我的一些文本中已经可以包含<br>标记(我只允许使用<br>),所以我只需要处理that...below,这只是我为此目的编写的额外代码。
对于看似微不足道的事情,它似乎很漫长吗?
//---All this to not break upon <br> --
if (text.includes('<br>')) {
var charAtMaxLength = text.charAt(maxLength).toLowerCase();
//console.log(charAtMaxLength);
switch (charAtMaxLength) {
case '<':
if (text.charAt(maxLength + 3).toLowerCase() === '>') {
//console.log('Decrease maxLength by 1');
maxLength -= 1;
}
break;
case 'b':
if (text.charAt(maxLength - 1).toLowerCase() === '<') {
//console.log('Decrease maxLength by 2');
maxLength -= 2;
}
break;
case 'r':
if (text.charAt(maxLength - 2).toLowerCase() === '<') {
//console.log('Decrease maxLength by 3');
maxLength -= 3;
}
break;
case '>':
if (text.charAt(maxLength - 3).toLowerCase() === '<') {
//console.log('Increase maxLength by 1');
maxLength += 1;
}
break;
default:
//Do nothing.
break;
}
//console.log(charAtMaxLength);
}
//--------------------------------------发布于 2016-08-17 16:31:39
您想要检查您匹配的字母是否是<br>的一部分。但你在做一项奇怪的检查。里面有虫子。
假设我们测试:
ad
我们说maxLength是1。你不会破坏<bc>的。为了对此进行干燥测试:
text.includes('<br>') # true
text.charAt(maxLength).toLowerCase() # '<'
switch ('<')
case '<':
text.charAt(maxLength + 3).toLowerCase() === '>' # true
maxLength -= 1 # maxLength = 0相反,您可以使用、indexOf、slice和length来检查是否不允许使用文本。这使得您可以轻松地更改要删除的内容,并对其进行扩展。却比你拥有的要小得多。
charAt。indexof it。maxLength减去index。index是否在删除字符串中,并检查从开始到开始的文本的slice加上remove字符串length是否是删除字符串。maxLength更改为start - 1。或者在JavaScript中:
var text = 'a<br>d<br>';
var remove = '<br>';
var maxLength = 4;
var char = text.charAt(maxLength).toLowerCase();
var index = remove.indexOf(char);
var start = maxLength - index;
if (index != -1 && text.slice(start, start + remove.length).toLowerCase() == remove) {
maxLength = start - 1;
}https://codereview.stackexchange.com/questions/138942
复制相似问题