IT박스

긴 문자열을 자르는 현명한 방법

itboxs 2020. 6. 10. 22:48
반응형

긴 문자열을 자르는 현명한 방법


누구나 JavaScript를 사용하여 문자열을 자르고 끝에 줄임표를 넣는보다 정교한 솔루션 / 라이브러리가 있습니까?

if(string.length > 25) {
    string = string.substring(0,24) + "...";
}

String.prototype.trunc = String.prototype.trunc ||
      function(n){
          return (this.length > n) ? this.substr(0, n-1) + '…' : this;
      };

이제 할 수있는 일 :

var s = 'not very long';
s.trunc(25); //=> not very long
s.trunc(5); //=> not ...

'더 정교'하여 문자열의 마지막 단어 경계에서 잘리는 것을 의미하는 경우 원하는 것이 될 수 있습니다.

String.prototype.trunc =
     function( n, useWordBoundary ){
         if (this.length <= n) { return this; }
         var subString = this.substr(0, n-1);
         return (useWordBoundary 
            ? subString.substr(0, subString.lastIndexOf(' ')) 
            : subString) + "&hellip;";
      };

지금 당신은 할 수 있습니다 :

s.trunc(11,true) // => not very...

기본 객체를 확장하지 않으려면 다음을 사용할 수 있습니다.

function truncate( n, useWordBoundary ){
    if (this.length <= n) { return this; }
    var subString = this.substr(0, n-1);
    return (useWordBoundary 
       ? subString.substr(0, subString.lastIndexOf(' ')) 
       : subString) + "&hellip;";
};
// usage
truncate.apply(s, [11, true]); // => not very...

이것은 Firefox에서만 수행해야합니다.

다른 모든 브라우저는 CSS 솔루션을 지원합니다 ( 지원 테이블 참조 ).

p {
    white-space: nowrap;
    width: 100%;                   /* IE6 needs any width */
    overflow: hidden;              /* "overflow" value must be different from  visible"*/ 
    -o-text-overflow: ellipsis;    /* Opera < 11*/
    text-overflow:    ellipsis;    /* IE, Safari (WebKit), Opera >= 11, FF > 6 */
}

아이러니 한 사실은 Mozilla MDC에서 해당 코드 스 니펫을 얻었습니다.


lodash의 잘림을 사용하십시오.

_.truncate('hi-diddly-ho there, neighborino');
// → 'hi-diddly-ho there, neighbo…'

또는 underscore.string의 truncate .

_('Hello world').truncate(5); => 'Hello...'

사람들이 CSS 대신 JavaScript로 이것을하기를 원하는 정당한 이유가 있습니다.

JavaScript에서 8 자 (줄임표 포함)로 자르려면

short = long.replace(/(.{7})..+/, "$1&hellip;");

또는

short = long.replace(/(.{7})..+/, "$1…");

다음은 다른 제안보다 개선 된 솔루션입니다.

String.prototype.truncate = function(){
    var re = this.match(/^.{0,25}[\S]*/);
    var l = re[0].length;
    var re = re[0].replace(/\s$/,'');
    if(l < this.length)
        re = re + "&hellip;";
    return re;
}

// "This is a short string".truncate();
"This is a short string"

// "Thisstringismuchlongerthan25characters".truncate();
"Thisstringismuchlongerthan25characters"

// "This string is much longer than 25 characters and has spaces".truncate();
"This string is much longer&hellip;"

그것:

  • 25 자 뒤 첫 공백에서 자릅니다.
  • JavaScript String 객체를 확장하여 모든 문자열에서 사용할 수 있습니다.
  • 잘림으로 인해 후행 공백이 생기면 문자열이 잘립니다.
  • 잘린 문자열이 25자를 초과하면 유니 코드 헬리콥터 엔티티 (줄임표)가 추가됩니다.

내가 찾은 최고의 기능. 텍스트 줄임표에 대한 크레딧 .

function textEllipsis(str, maxLength, { side = "end", ellipsis = "..." } = {}) {
  if (str.length > maxLength) {
    switch (side) {
      case "start":
        return ellipsis + str.slice(-(maxLength - ellipsis.length));
      case "end":
      default:
        return str.slice(0, maxLength - ellipsis.length) + ellipsis;
    }
  }
  return str;
}

:

var short = textEllipsis('a very long text', 10);
console.log(short);
// "a very ..."

var short = textEllipsis('a very long text', 10, { side: 'start' });
console.log(short);
// "...ng text"

var short = textEllipsis('a very long text', 10, { textEllipsis: ' END' });
console.log(short);
// "a very END"

대부분의 현대 자바 스크립트 프레임 워크 ( JQuery와 , 프로토 타입 , ...) 그 핸들이 String에 식은 유틸리티 기능을 가지고있다.

다음은 프로토 타입의 예입니다.

'Some random text'.truncate(10);
// -> 'Some ra...'

이것은 다른 사람이 다루거나 유지하기를 원하는 기능 중 하나처럼 보입니다. 더 많은 코드를 작성하는 대신 프레임 워크가 처리하도록하겠습니다.


모든 최신 브라우저는 이제 텍스트 줄이 사용 가능한 너비를 초과하면 줄임표를 자동으로 추가하기위한 간단한 CSS 솔루션을 지원합니다.

p {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

(효과를 주려면 요소의 너비를 어떤 식 으로든 제한해야합니다.)

https://css-tricks.com/snippets/css/truncate-string-with-ellipsis/를 기반으로 합니다.

이 방법은 문자 수에 따라 제한 되지 않습니다 . 여러 줄의 텍스트를 허용해야하는 경우 에도 작동하지 않습니다 .


아마도 누군가가 null을 처리하는 위치의 예를 놓쳤을 수도 있지만 null이있을 때 3 개의 TOP 답변이 효과가 없었습니다 (물론 오류 처리가 있고 백만 가지가 질문에 대답하는 사람의 책임이 아니라는 것을 알고 있습니다. 기존 기능을 다른 잘림 줄임표 답변 중 하나와 함께 사용하여 다른 사람에게 제공 할 것이라고 생각했습니다.

예 :

자바 스크립트 :

news.comments

절단 기능 사용

news.comments.trunc(20, true);

그러나 news.comments가 null 인 경우 "단절"

결정적인

checkNull(news.comments).trunc(20, true) 

KooiInc의 trunc 기능 제공

String.prototype.trunc =
 function (n, useWordBoundary) {
     console.log(this);
     var isTooLong = this.length > n,
         s_ = isTooLong ? this.substr(0, n - 1) : this;
     s_ = (useWordBoundary && isTooLong) ? s_.substr(0, s_.lastIndexOf(' ')) : s_;
     return isTooLong ? s_ + '&hellip;' : s_;
 };

내 간단한 null 검사기 (리터럴 "null"항목도 검사합니다 (정의되지 않은 "", null, "null"등을 잡습니다.)

  function checkNull(val) {
      if (val) {
          if (val === "null") {
              return "";
          } else {
              return val;
          }
      } else {
          return "";
      }
  }

때로는 파일 이름이 번호가 매겨져 색인이 시작 또는 끝에있을 수 있습니다. 그래서 줄의 중심에서 짧게하고 싶었습니다.

function stringTruncateFromCenter(str, maxLength) {
    const midChar = "…";      // character to insert into the center of the result
    var left, right;

    if (str.length <= maxLength) return str;

    // length of beginning part      
    left = Math.ceil(maxLength / 2);

    // start index of ending part   
    right = str.length - Math.floor(maxLength / 2) + 1;   

    return str.substr(0, left) + midChar + str.substring(right);
}

UTF-8에서 1 바이트 이상으로 채우기 문자를 사용했습니다.


Ext.js 를 사용하는 경우 Ext.util.Format.ellipsis 함수를 사용할 수 있습니다.


나는 Kooilnc의 솔루션을 찬성했습니다. 정말 멋진 컴팩트 솔루션. 내가 다루고 싶은 작은 경우가 하나 있습니다. 어떤 이유로 든 누군가가 긴 문자 시퀀스를 입력하면 잘리지 않습니다.

function truncate(str, n, useWordBoundary) {
    var singular, tooLong = str.length > n;
    useWordBoundary = useWordBoundary || true;

    // Edge case where someone enters a ridiculously long string.
    str = tooLong ? str.substr(0, n-1) : str;

    singular = (str.search(/\s/) === -1) ? true : false;
    if(!singular) {
      str = useWordBoundary && tooLong ? str.substr(0, str.lastIndexOf(' ')) : str;
    }

    return  tooLong ? str + '&hellip;' : str;
}

빠른 인터넷 검색으로 이것을 발견 했습니다 ... 그것이 효과가 있습니까?

/**
 * Truncate a string to the given length, breaking at word boundaries and adding an elipsis
 * @param string str String to be truncated
 * @param integer limit Max length of the string
 * @return string
 */
var truncate = function (str, limit) {
    var bits, i;
    if (STR !== typeof str) {
        return '';
    }
    bits = str.split('');
    if (bits.length > limit) {
        for (i = bits.length - 1; i > -1; --i) {
            if (i > limit) {
                bits.length = i;
            }
            else if (' ' === bits[i]) {
                bits.length = i;
                break;
            }
        }
        bits.push('...');
    }
    return bits.join('');
};
// END: truncate

c_harm의 대답은 제 생각으로는 최고입니다. 사용하고 싶은 경우는 양해 바랍니다

"My string".truncate(n)

you will have to use a regexp object constructor rather than a literal. Also you'll have to escape the \S when converting it.

String.prototype.truncate =
    function(n){
        var p  = new RegExp("^.{0," + n + "}[\\S]*", 'g');
        var re = this.match(p);
        var l  = re[0].length;
        var re = re[0].replace(/\s$/,'');

        if (l < this.length) return re + '&hellip;';
    };

Use following code

 function trancateTitle (title) {
    var length = 10;
    if (title.length > length) {
       title = title.substring(0, length)+'...';
    }
    return title;
}

Correcting Kooilnc's solution:

String.prototype.trunc = String.prototype.trunc ||
  function(n){
      return this.length>n ? this.substr(0,n-1)+'&hellip;' : this.toString();
  };

This returns the string value instead of the String object if it doesn't need to be truncated.


I recently had to do this and ended up with:

/**
 * Truncate a string over a given length and add ellipsis if necessary
 * @param {string} str - string to be truncated
 * @param {integer} limit - max length of the string before truncating
 * @return {string} truncated string
 */
function truncate(str, limit) {
    return (str.length < limit) ? str : str.substring(0, limit).replace(/\w{3}$/gi, '...');
}

Feels nice and clean to me :)


I like using .slice() The first argument is the starting index and the second is the ending index. Everything in between is what you get back.

var long = "hello there! Good day to ya."
// hello there! Good day to ya.

var short  = long.slice(0, 5)
// hello

Somewhere Smart :D

//My Huge Huge String
    let tooHugeToHandle = `It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).`
    
//Trim Max Length
 const maxValue = 50
// The barber.
 const TrimMyString = (string, maxLength, start = 0) => {
//Note - `start` is if I want to start after some point of the string
    	if (string.length > maxLength) {
    	let trimmedString = string.substr(start, maxLength)
    	 return (
    	   trimmedString.substr(
    	   start,
    	   Math.min(trimmedString.length,   trimmedString.lastIndexOf(' '))
           ) + ' ...'
         )
       }
    return string
}

console.log(TrimMyString(tooHugeToHandle, maxValue))


.wrap{
  text-overflow: ellipsis
  white-space: nowrap;
  overflow: hidden;
  width:"your desire width";
}
<p class="wrap">He this is code</p>

('long text to be truncated').replace(/(.{250})..+/, "$1…");

Somehow above code was not working for some kind of copy pasted or written text in vuejs app. So I used lodash truncate and its now working fine.

_.truncate('long text to be truncated', { 'length': 250, 'separator': ' '});

This function do the truncate space and words parts also.(ex: Mother into Moth...)

String.prototype.truc= function (length) {
        return this.length>length ? this.substring(0, length) + '&hellip;' : this;
};

usage:

"this is long length text".trunc(10);
"1234567890".trunc(5);

output:

this is lo...

12345...

참고URL : https://stackoverflow.com/questions/1199352/smart-way-to-truncate-long-strings

반응형