缩短字符串而不在JavaScript中剪切单词 [英] Shorten string without cutting words in JavaScript

查看:92
本文介绍了缩短字符串而不在JavaScript中剪切单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JavaScript中的字符串操作不太熟悉,我想知道如何在不删除任何字的情况下缩短字符串。我知道如何使用substring,但不知道indexOf或其他任何东西。

I'm not very good with string manipulation in JavaScript, and I was wondering how you would go about shortening a string without cutting any word off. I know how to use substring, but not indexOf or anything really well.

说我有以下字符串:

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

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

I want to trim it down to 10 characters, but if it doesn't end with a space, finish the word. I don't want the string variable to look like this:


这是一个很长的字符串我不能说

"this is a long string I cant dis"

我想让它完成这个词直到空格出现。

I want it to finish the word until a space occurs.

推荐答案

如果我理解正确,你想要将一个字符串缩短到一定的长度(例如缩短快速的棕色狐狸跳过懒狗到,比如说,6个字符没有删掉任何单词)。

If I understand correctly, you want to shorten a string to a certain length (e.g. shorten "The quick brown fox jumps over the lazy dog" to, say, 6 characters without cutting off any word).

如果是这种情况,您可以尝试以下内容:

If this is the case, you can try something like the following:

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中剪切单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆