자바스크립트에서 단어를 자르지 않고 문자열을 단축합니다.
저는 자바스크립트의 문자열 조작에 소질이 없는데, 어떤 단어도 끊지 않고 문자열을 짧게 하는 방법이 궁금했습니다.저는 서브스트링을 사용할 줄은 알지만 인덱스 Of나 다른 것은 잘 사용하지 않습니다.
내게 다음과 같은 문자열이 있다고 가정합니다.
text = "this is a long string I cant display"
10자로 줄이고 싶은데 띄어쓰기로 끝나지 않으면 단어를 끝냅니다.문자열 변수가 이렇게 나타나지 않았으면 합니다.
"이것은 내가 풀 수 없는 긴 문자열입니다."
공백이 생길 때까지 끝맺기를 원합니다.
내가 제대로 이해했다면, 문자열을 특정 길이(예: 줄이기)로 줄이려는 것입니다."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(" ")))
여러 가지 방법이 있지만 정규식은 유용한 한 줄 방법입니다.
"this is a longish string of text".replace(/^(.{11}[^\s]*).*/, "$1");
//"this is a longish"
이 식은 처음 11자(임의)와 그 이후의 공백이 아닌 문자를 모두 반환합니다.
스크립트 예제:
<pre>
<script>
var t = "this is a longish string of text";
document.write("1: " + t.replace(/^(.{1}[^\s]*).*/, "$1") + "\n");
document.write("2: " + t.replace(/^(.{2}[^\s]*).*/, "$1") + "\n");
document.write("5: " + t.replace(/^(.{5}[^\s]*).*/, "$1") + "\n");
document.write("11: " + t.replace(/^(.{11}[^\s]*).*/, "$1") + "\n");
document.write("20: " + t.replace(/^(.{20}[^\s]*).*/, "$1") + "\n");
document.write("100: " + t.replace(/^(.{100}[^\s]*).*/, "$1") + "\n");
</script>
출력:
1: this
2: this
5: this is
11: this is a longish
20: this is a longish string
100: this is a longish string of text
이와 같은 간단한 문제에 대해서는 읽기 어려운 답이 너무 많고 선택한 답을 포함한 어떤 것들은 효과가 없다는 것에 저는 다소 놀라고 있습니다.
보통 결과 문자열이 많아야 합니다. maxLen
성격. 저도 합니다. 저는 기능을 사용하여 의 URL 슬러그를 단축합니다 이 단축합니다 슬러그를 저는 사용하여 to use this url shorten 성격 i function same also the 이 url s
str.lastIndexOf(searchValue[, fromIndex])
두 번째 매개 변수는 문자열에서 뒤로 검색을 시작하여 작업을 효율적이고 단순하게 만드는 인덱스입니다.
// Shorten a string to less than maxLen characters without truncating words.
function shorten(str, maxLen, separator = ' ') {
if (str.length <= maxLen) return str;
return str.substr(0, str.lastIndexOf(separator, maxLen));
}
다음은 샘플 출력입니다.
for (var i = 0; i < 50; i += 3)
console.log(i, shorten("The quick brown fox jumps over the lazy dog", i));
0 ""
3 "The"
6 "The"
9 "The quick"
12 "The quick"
15 "The quick brown"
18 "The quick brown"
21 "The quick brown fox"
24 "The quick brown fox"
27 "The quick brown fox jumps"
30 "The quick brown fox jumps over"
33 "The quick brown fox jumps over"
36 "The quick brown fox jumps over the"
39 "The quick brown fox jumps over the lazy"
42 "The quick brown fox jumps over the lazy"
45 "The quick brown fox jumps over the lazy dog"
48 "The quick brown fox jumps over the lazy dog"
그리고 민달팽이의 경우:
for (var i = 0; i < 50; i += 10)
console.log(i, shorten("the-quick-brown-fox-jumps-over-the-lazy-dog", i, '-'));
0 ""
10 "the-quick"
20 "the-quick-brown-fox"
30 "the-quick-brown-fox-jumps-over"
40 "the-quick-brown-fox-jumps-over-the-lazy"
indexOf가 일치할 문자열과 보기 시작할 문자 색인의 두 가지 인수를 사용한다는 사실을 모두가 잊어버린 것 같습니다.10자 이후 첫 번째 칸에서 줄을 끊을 수 있습니다.
function cutString(s, n){
var cut= s.indexOf(' ', n);
if(cut== -1) return s;
return s.substring(0, cut)
}
var s= "this is a long string i cant display";
cutString(s, 10)
/* returned value: (String)
this is a long
*/
Lodash에는 다음과 같은 기능이 있습니다.
const truncate = _.truncate
const str = 'The quick brown fox jumps over the lazy dog'
truncate(str, {
length: 30, // maximum 30 characters
separator: /,?\.* +/ // separate by spaces, including preceding commas and periods
})
// 'The quick brown fox jumps...'
여기 한 줄에 해결책이 있습니다.
text = "this is a long string I cant display"
function shorten(text,max) {
return text && text.length > max ? text.slice(0,max).split(' ').slice(0, -1).join(' ') : text
}
console.log(shorten(text,10));
일부 코너 케이스를 처리하지 않는 NT3RP 답변을 바탕으로 이 코드를 만들었습니다.> ellipsis size > maxLength트다을지를을진a을het지t>aontxtn진h...
마지막에 추가되었습니다.
이것은 또한 하나의 단어가 > maxLength인 텍스트와 같은 일부 코너 케이스를 처리합니다.
shorten: function(text,maxLength,options) {
if ( text.length <= maxLength ) {
return text;
}
if ( !options ) options = {};
var defaultOptions = {
// By default we add an ellipsis at the end
suffix: true,
suffixString: " ...",
// By default we preserve word boundaries
preserveWordBoundaries: true,
wordSeparator: " "
};
$.extend(options, defaultOptions);
// Compute suffix to use (eventually add an ellipsis)
var suffix = "";
if ( text.length > maxLength && options.suffix) {
suffix = options.suffixString;
}
// Compute the index at which we have to cut the text
var maxTextLength = maxLength - suffix.length;
var cutIndex;
if ( options.preserveWordBoundaries ) {
// We use +1 because the extra char is either a space or will be cut anyway
// This permits to avoid removing an extra word when there's a space at the maxTextLength index
var lastWordSeparatorIndex = text.lastIndexOf(options.wordSeparator, maxTextLength+1);
// We include 0 because if have a "very long first word" (size > maxLength), we still don't want to cut it
// But just display "...". But in this case the user should probably use preserveWordBoundaries:false...
cutIndex = lastWordSeparatorIndex > 0 ? lastWordSeparatorIndex : maxTextLength;
} else {
cutIndex = maxTextLength;
}
var newText = text.substr(0,cutIndex);
return newText + suffix;
}
이것이 당신을 괴롭힌다면 쉽게 jquery dependence를 제거할 수 있을 것 같습니다.
파티에 늦었지만, 여기 제가 생각해낸 작고 쉬운 해결책이 있습니다.
당신이 원하는 캐릭터와 직접적인 관련은 없지만, 당신이 추구했던 것과 같은 결과를 가져다 줍니다.
function truncateWords(sentence, amount, tail) {
const words = sentence.split(' ');
if (amount >= words.length) {
return sentence;
}
const truncated = words.slice(0, amount);
return `${truncated.join(' ')}${tail}`;
}
const sentence = 'Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.';
console.log(truncateWords(sentence, 10, '...'));
여기서 작동 예를 참조하십시오. https://jsfiddle.net/bx7rojgL/
function shorten(str,n) {
return (str.match(RegExp(".{"+n+"}\\S*"))||[str])[0];
}
shorten("Hello World", 3); // "Hello"
// SHORTEN STRING TO WHOLE WORDS
function shorten(s,l) {
return (s.match(new RegExp(".{"+l+"}\\S*"))||[s])[0];
}
console.log( shorten("The quick brown fox jumps over the lazy dog", 6) ); // "The quick"
저는 다른 접근법을 취했습니다.저는 비슷한 결과가 필요했지만, 반품 값을 지정된 길이보다 작게 유지하고 싶었습니다.
function wordTrim(value, length, overflowSuffix) {
value = value.trim();
if (value.length <= length) return value;
var strAry = value.split(' ');
var retString = strAry[0];
for (var i = 1; i < strAry.length; i++) {
if (retString.length >= length || retString.length + strAry[i].length + 1 > length) break;
retString += " " + strAry[i];
}
return retString + (overflowSuffix || '');
}
편집 여기서 약간 리팩터링했습니다: JS Fiddle 예제.연결 대신 원래 배열을 다시 결합합니다.
function wordTrim(value, length, overflowSuffix) {
if (value.length <= length) return value;
var strAry = value.split(' ');
var retLen = strAry[0].length;
for (var i = 1; i < strAry.length; i++) {
if(retLen == length || retLen + strAry[i].length + 1 > length) break;
retLen+= strAry[i].length + 1
}
return strAry.slice(0,i).join(' ') + (overflowSuffix || '');
}
이는 최종 단어를 포함하는 대신 제외하는 것입니다.
function smartTrim(str, length, delim, appendix) {
if (str.length <= length) return str;
var trimmedStr = str.substr(0, length+delim.length);
var lastDelimIndex = trimmedStr.lastIndexOf(delim);
if (lastDelimIndex >= 0) trimmedStr = trimmedStr.substr(0, lastDelimIndex);
if (trimmedStr) trimmedStr += appendix;
return trimmedStr;
}
용도:
smartTrim(yourString, 11, ' ', ' ...')
"The quick ..."
을 사용할 수 .truncate
아래의 한 줄:
const text = "The string that I want to truncate!";
const truncate = (str, len) => str.substring(0, (str + ' ').lastIndexOf(' ', len));
console.log(truncate(text, 14));
타자기, 타원 포함 :)
export const sliceByWord = (phrase: string, length: number, skipEllipses?: boolean): string => {
if (phrase.length < length) return phrase
else {
let trimmed = phrase.slice(0, length)
trimmed = trimmed.slice(0, Math.min(trimmed.length, trimmed.lastIndexOf(' ')))
return skipEllipses ? trimmed : trimmed + '…'
}
}
다음은 유용한 속성이 몇 가지 있는 한 줄 버전입니다.
- 에 하는 의 을 합니다 합니다 을 하는 의
\s
- 입력 길이에 관계없이 수행(최대 길이를 초과하는 항목은 스캔하지 않음)
- 출력 길이에 관계없이 수행합니다(최대 길이에서 뒤로 스캔하여 문자열을 분할/결합하지 않음).
s.length > maxLen ? s.substring(0, s.substring(0, maxLen + 1).search(/\s+\S*$/)) : s
lodash 라이브러리를 사용하는 경우 문자열을 트리밍하는 데 사용할 수 있는 truncate 함수가 있습니다.
문서 페이지의 예제를 기반으로 합니다.
_.truncate('hi-diddly-ho there, neighborino', {
'length': 24,
'separator': ' '
});
// => 'hi-diddly-ho there,...'
const title = "Hello world is not the way to go"
const trimmedTitle = title.split(" ").slice(0, 4).join(" ");
// 출력: "Hello world is not"
문자열 끝에 구두점이나 공백을 남기지 않고 단어 경계로 자르기 위해 이 글을 썼습니다.
function truncateStringToWord(str, length, addEllipsis)
{
if(str.length <= length)
{
// provided string already short enough
return(str);
}
// cut string down but keep 1 extra character so we can check if a non-word character exists beyond the boundary
str = str.substr(0, length+1);
// cut any non-whitespace characters off the end of the string
if (/[^\s]+$/.test(str))
{
str = str.replace(/[^\s]+$/, "");
}
// cut any remaining non-word characters
str = str.replace(/[^\w]+$/, "");
var ellipsis = addEllipsis && str.length > 0 ? '…' : '';
return(str + ellipsis);
}
var testString = "hi stack overflow, how are you? Spare";
var i = testString.length;
document.write('<strong>Without ellipsis:</strong><br>');
while(i > 0)
{
document.write(i+': "'+ truncateStringToWord(testString, i) +'"<br>');
i--;
}
document.write('<strong>With ellipsis:</strong><br>');
i = testString.length;
while(i > 0)
{
document.write(i+': "'+ truncateStringToWord(testString, i, true) +'"<br>');
i--;
}
shorten(str, maxLen, appendix, separator = ' ') {
if (str.length <= maxLen) return str;
let strNope = str.substr(0, str.lastIndexOf(separator, maxLen));
return (strNope += appendix);
}
vars= "이것은 긴 문자열이므로 모두 설명할 수 없습니다."; shorten(s, 10, '...')
/* "이건.." */
문장부호를 따라 자르는 또 다른 코드 조각이 있습니다. (이것을 찾고 있었는데 Google에서 이 질문을 발견했습니다.)스스로 해결책을 마련해야 했기 때문에 15분 만에 해킹을 했습니다.. ! ? 의 모든 경우를 찾고 다음 위치에서 자릅니다.len
function pos(str, char) {
let pos = 0
const ret = []
while ( (pos = str.indexOf(char, pos + 1)) != -1) {
ret.push(pos)
}
return ret
}
function truncate(str, len) {
if (str.length < len)
return str
const allPos = [ ...pos(str, '!'), ...pos(str, '.'), ...pos(str, '?')].sort( (a,b) => a-b )
if (allPos.length === 0) {
return str.substr(0, len)
}
for(let i = 0; i < allPos.length; i++) {
if (allPos[i] > len) {
return str.substr(0, allPos[i-1] + 1)
}
}
}
module.exports = truncate
'토마토와 시금치를 곁들인 파스타'
말을 반으로 자르기 싫으면
첫 번째 반복:
acc:0 / acc +cur.길이 = 5 / newTitle = ['파스타'];
두 번째 반복:
acc:5 / acc + cur.길이 = 9 / newTitle = ['파스타', 'with'];
세 번째 반복:
acc:9 / acc + cur.길이 = 15 / newTitle = ['파스타', 'with', 'with', 'float'];
네 번째 반복:
acc:15 / acc + cur.길이 = 18(병렬 바운드) / newTitle = ['파스타', 'with', 'with', 'float'];
const limitRecipeTitle = (title, limit=17)=>{
const newTitle = [];
if(title.length>limit){
title.split(' ').reduce((acc, cur)=>{
if(acc+cur.length <= limit){
newTitle.push(cur);
}
return acc+cur.length;
},0);
}
return `${newTitle.join(' ')} ...`
}
출력 : 토마토가 들어간 파스타...
키스 앤서
'this is a string'.split(' ').reduce((a, b) => (a+b).length < 10 ? a+' '+b : a);
투표한 솔루션이 만족스럽지 못했습니다.그래서 저는 일종의 포괄적이고 텍스트의 첫 번째 부분과 마지막 부분 모두에서 작동하는 것(서브스터 같은 것이지만 단어를 위한 것)을 썼습니다.또한 샤 카운트에서 공백을 제외하고 싶은 경우 설정할 수 있습니다.
function chopTxtMinMax(txt, firstChar, lastChar=0){
var wordsArr = txt.split(" ");
var newWordsArr = [];
var totalIteratedChars = 0;
var inclSpacesCount = true;
for(var wordIndx in wordsArr){
totalIteratedChars += wordsArr[wordIndx].length + (inclSpacesCount ? 1 : 0);
if(totalIteratedChars >= firstChar && (totalIteratedChars <= lastChar || lastChar==0)){
newWordsArr.push(wordsArr[wordIndx]);
}
}
txt = newWordsArr.join(" ");
return txt;
}
이것 때문에 늦게 왔는데 이 기능이 OP가 요청하는 것을 정확하게 만들어 주는 것 같습니다.SENTENT와 LIMIT 값을 다른 결과로 쉽게 변경할 수 있습니다.
function breakSentence(word, limit) {
const queue = word.split(' ');
const list = [];
while (queue.length) {
const word = queue.shift();
if (word.length >= limit) {
list.push(word)
}
else {
let words = word;
while (true) {
if (!queue.length ||
words.length > limit ||
words.length + queue[0].length + 1 > limit) {
break;
}
words += ' ' + queue.shift();
}
list.push(words);
}
}
return list;
}
const SENTENCE = 'the quick brown fox jumped over the lazy dog';
const LIMIT = 11;
// get result
const words = breakSentence(SENTENCE, LIMIT);
// transform the string so the result is easier to understand
const wordsWithLengths = words.map((item) => {
return `[${item}] has a length of - ${item.length}`;
});
console.log(wordsWithLengths);
이 토막글의 출력은 LIMIT가 11인 경우입니다.
[ '[the quick] has a length of - 9',
'[brown fox] has a length of - 9',
'[jumped over] has a length of - 11',
'[the lazy] has a length of - 8',
'[dog] has a length of - 3' ]
빈 문장과 매우 긴 첫 단어와 같은 경계 조건이 있습니다.또한 언어 특정 문자열 api/library를 사용하지 않습니다.
function solution(message, k) {
if(!message){
return ""; //when message is empty
}
const messageWords = message.split(" ");
let result = messageWords[0];
if(result.length>k){
return ""; //when length of first word itself is greater that k
}
for(let i = 1; i<messageWords.length; i++){
let next = result + " " + messageWords[i];
if(next.length<=k){
result = next;
}else{
break;
}
}
return result;
}
console.log(solution("this is a long string i cant display", 10));
우리는 lodash의 잘라내기 기능을 사용함으로써 이것을 쉽게 할 수 있습니다.
_.truncate('hi-diddly-ho there, neighborino');
// => 'hi-diddly-ho there, neighbo...'
_.truncate('hi-diddly-ho there, neighborino', {
'length': 24,
'separator': ' '
});
// => 'hi-diddly-ho there,...'
자세한 내용은 Lodash Documentation을 참조하십시오.
@NT3RP에서 업데이트한 결과 문자열이 처음으로 빈칸에 닿으면 해당 단어가 삭제되어 문자열이 가능한 한 단어보다 짧은 단어가 됩니다.그래서 maxLength가 공간에 떨어지지 않는지 확인하기 위해 if other statement를 넣었습니다.
var yourString = "The quick brown fox jumps over the lazy dog"; //replace with your string.
var maxLength = 15 // maximum number of characters to extract
if (yourString[maxLength] !== " ") {
//trim the string to the maximum length
var trimmedString = yourString.substr(0, maxLength);
alert(trimmedString)
//re-trim if we are in the middle of a word
trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")))
}
else {
var trimmedString = yourString.substr(0, maxLength);
}
alert(trimmedString)
당신은 다음과 같은 자바스크립트 방법을 사용할 수 있습니다.substring
:
var content = "ABCD";
content.substring(0, 2);
console.log(content);
예상 출력은"D"
"ABC"
사용 가능한 내용이 다음과 같이 다듬어집니다."D"
언급URL : https://stackoverflow.com/questions/5454235/shorten-string-without-cutting-words-in-javascript
'it-source' 카테고리의 다른 글
Angular2 \ Typcript에서 문자열을 날짜로 변환하는 방법? (0) | 2023.09.08 |
---|---|
장고에서 X 편집 가능한 인라인 편집 - CSRF 보호를 받는 방법은? (0) | 2023.09.08 |
필요한 인수 전달(모듈 로드 시) (0) | 2023.09.08 |
Android 앱에서 Excel 파일 보기 (0) | 2023.09.08 |
Android Studio에서 Parameterized Unit 테스트를 실행할 때 오류가 발생한 테스트가 없습니다. (0) | 2023.09.08 |