「テスト用のサンプルテキスト」というテキストがあります。私はdivに10文字だけを表示する必要があります。 ので、私はこれが私の「サンプルT」を与えるテキストjavascriptを使用して全文のみを表示する
txt.substring(0,10)
にサブストリングありません。終わりのない言葉を表示するのは醜いので、表示するには "サンプル"を表示するだけでよいです。私はこれをどのようにして行うのですか?
「テスト用のサンプルテキスト」というテキストがあります。私はdivに10文字だけを表示する必要があります。 ので、私はこれが私の「サンプルT」を与えるテキストjavascriptを使用して全文のみを表示する
txt.substring(0,10)
にサブストリングありません。終わりのない言葉を表示するのは醜いので、表示するには "サンプル"を表示するだけでよいです。私はこれをどのようにして行うのですか?
テキストを10文字に部分文字列で区切って入力することもできます。
次に、テキストの最後のスペースを見つけるためにtxt.lastIndexOf( '')を使用します。
次に、テキストを部分文字列に再使用します。
例:
var txt = "A Sample Text";
txt = txt.subString(0,10); // "A Sample T"
txt = txt.subString(0, txt.lastIndexOf(' ')); // "A Sample"
ことができますなら、私を知ってみましょう!
単語が長い10文字を超える場合は、むしろ、空の文字列よりもカットオフ文字列を持っているだろうと仮定すると:この を行うための方法をサブストリング
function shorten(txt)
{
// if it's short or a space appears after the first 10 characters, keep the substring (simple case)
if (txt.length <= 10 || txt[10] === ' ') return txt;
// get the index of the last space
var i = txt.substring(0, 11).lastIndexOf(' ');
// if a space is found, return the whole words at the start of the string;
// otherwise return just the first 10 characters
return txt.substring(0, i === -1 ? 11 : i);
}
使用することは、私はあなたがフィルタを追加すべきだと思います部分文字列の方法で11番目の文字が空白かどうかを調べます。さもなければ最後の有効な単語も削除される可能性があります。たとえば、「テスト用の新しいサンプルテキスト」を取得します。
これはコードです。
str = "A sample text for testing"
ch11_space = (str[10] == ' ') ? 0 : 1;
str = str.substring(0,10);
if (ch11_space) {
str = str.substring(0,str.lastIndexOf(' '));
}
function getShortenedString(str)
{
var maxLength = 10; // whatever the max string can be
var strLength = str.length;
var shortenedStr = str.substr(0, maxLength);
var shortenedStrLength = shortenedStr.length;
var lastSpace = str.lastIndexOf(" ");
if(shortenedStrLength != strLength)
{
// only need to do manipulation if we have a shortened name
var strDiff = strLength - shortenedStrLength;
var lastSpaceDiff = shortenedStrLength - lastSpace;
if(strDiff > lastSpaceDiff) // non-whole word after space
{
shortenedStr = str.substr(0, lastSpace);
}
}
return shortenedStr;
}
あなたはすべての単語が大文字たいですか?そして、 "Stackoverflow"(10文字以上)をどのように表示したいですか? – Thilo
@Thilo私は常にこれを一言ではなく一文で使います。これは問題ではありません。 – DDK