我正在使用以下函數來截斷在其旁邊有一個"read more"
按鈕的文本。在JavaScript中截斷文本,不包含html元素
truncateText: function (string, targetCharacterLength) {
var length = string.length;
if (length < targetCharacterLength) {
return (string)
} else {
var shortenedString = string.slice(0, targetCharacterLength);
shortenedString = shortenedString.slice(0,shortenedString.lastIndexOf(' ')) + '... ';
return shortenedString
}
}
所以我的問題是與<a>
標籤內的文字。如果它剛好在"read more"
按鈕之前開始,則該按鈕的功能會中斷。
這是我看到的時候我在哪裏的<a>
標籤開始只是"..."
< a... < a="" href="#" class="more" > Read More < /a...>
之前有沒有人對我怎樣才能解決這一問題的思路文本檢查元素?我無法使用插件。
感謝
你想保持聯繫作爲截斷的字符串鏈接?如果沒關係,可以將該字符串作爲純文本發送到函數中。 –
這可能是你要找的東西:https://www.npmjs.com/package/htmlsave – Martijn