文字ではなく単語で substr を制限したいと思います。正規表現とスペースを考えていますが、それをやってのける方法がわかりません。
シナリオ: javascript/jQuery を使用して、単語の段落を 200 単語に制限します。
var $postBody = $postBody.substr(' ',200);
これは素晴らしいですが、単語を半分に分割します:) 事前に感謝します!
文字ではなく単語で substr を制限したいと思います。正規表現とスペースを考えていますが、それをやってのける方法がわかりません。
シナリオ: javascript/jQuery を使用して、単語の段落を 200 単語に制限します。
var $postBody = $postBody.substr(' ',200);
これは素晴らしいですが、単語を半分に分割します:) 事前に感謝します!
function trim_words(theString, numWords) {
expString = theString.split(/\s+/,numWords);
theNewString=expString.join(" ");
return theNewString;
}
if you're satisfied with a not-quite accurate solution, you could simply keep a running count on the number of space characters within the text and assume that it is equal to the number of words.
Otherwise, I would use split() on the string with " " as the delimiter and then count the size of the array that split returns.
句読点やその他の単語や空白以外の文字も考慮する必要があると思います。空白や文字以外の文字を数えずに、200語が必要です。
var word_count = 0;
var in_word = false;
for (var x=0; x < text.length; x++) {
if ( ... text[x] is a letter) {
if (!in_word) word_count++;
in_word = true;
} else {
in_word = false;
}
if (!in_word && word_count >= 200) ... cut the string at "x" position
}
また、数字を単語として扱うかどうか、および1文字を単語として扱うかどうかも決定する必要があります。
非常に速くて汚い
$("#textArea").val().split(/\s/).length