javascript - 缩短字符串而不切割 JavaScript 中的单词

标签 javascript string substring

我不太擅长 JavaScript 中的字符串操作,我想知道如何在不删掉任何单词的情况下缩短字符串。我知道如何使用子字符串,但不知道如何使用 indexOf 或其他任何东西。

假设我有以下字符串:

text = "this is a long string I cant display"

我想将它缩减为 10 个字符,但如果它没有以空格结尾,请完成这个词。我不希望字符串变量看起来像这样:

"this is a long string I cant dis"

我希望它完成单词直到出现空格。

最佳答案

如果我理解正确,你想将字符串缩短到一定长度(例如,将 "The quick brown fox jumps over the lazy dog" 缩短为 6 个字符而不切断任何单词).

如果是这种情况,您可以尝试以下操作:

var yourString = "The quick brown fox jumps over the lazy dog"; //replace with your string.
var maxLength = 6 // maximum number of characters to extract

//trim the string to the maximum length
var trimmedString = yourString.substr(0, maxLength);

//re-trim if we are in the middle of a word
trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")))

关于javascript - 缩短字符串而不切割 JavaScript 中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5454235/

相关文章:

c# - 什么是 C# 中的 Java 子字符串?

sql - 如何根据 HiveQL 和 SQL 中特定列的子字符串进行选择?

javascript - 关于日期和 cookie 的奇怪问题

javascript - 是否可以使用 JavaScript 从浏览器检索用户的主页 URL?

algorithm - 帮助我优化索引字符串搜索

java - 为什么一个String不指向String池中的同一个对象?

javascript - 如何在从字符串构建的 HTML 中设置事件?

javascript - 如何使用 jquery 使 div 可见?

javascript - 将选中的复选框推送到数组并从数组中获取值以构建查询字符串

java - 如何找到以给定字符串开头的单词?