programing

Javascript에서 문자열을 N자로 트리밍하는 방법은?

sourcetip 2022. 9. 5. 23:37
반응형

Javascript에서 문자열을 N자로 트리밍하는 방법은?

Javascript를 사용하여 인수로 전달된 문자열과 인수로 전달된 문자열을 지정된 길이로 잘라내는 함수를 만들려면 어떻게 해야 합니까?예를 들어 다음과 같습니다.

var string = "this is a string";
var length = 6;
var trimmedString = trimFunction(length, string);

// trimmedString should be:
// "this is"

아이디어 있는 사람?서브스트링 사용에 대해 들은 적은 있지만 잘 이해하지 못했습니다.

왜 그냥 서브스트링을 사용하지 않는 거죠? string.substring(0, 7);첫 번째 인수(0)가 시작점입니다.두 번째 인수(7)는 끝점(배타적)이다.자세한 것은 이쪽.

var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);

윌의 코멘트를 답변에 복사하는 은 도움이 된다는 것을 알게 되었기 때문입니다.

var string = "this is a string";
var length = 20;
var trimmedString = string.length > length ? 
                    string.substring(0, length - 3) + "..." : 
                    string;

고마워요 윌

또한 https://jsfiddle.net/t354gw7e/를 관심있는 분들을 위한 jsfiddle도 준비되어 있습니다.

코드 깔끔함을 위해 확장자를 사용하는 것이 좋습니다.내부 객체 프로토타입을 확장하면 해당 프로토타입을 사용하는 라이브러리가 손상될 수 있습니다.

String.prototype.trimEllip = function (length) {
  return this.length > length ? this.substring(0, length) + "..." : this;
}

사용법은 다음과 같습니다.

var stringObject= 'this is a verrrryyyyyyyyyyyyyyyyyyyyyyyyyyyyylllooooooooooooonggggggggggggsssssssssssssttttttttttrrrrrrrrriiiiiiiiiiinnnnnnnnnnnnggggggggg';
stringObject.trimEllip(25)

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substr

링크에서:

string.substr(start[, length])
    let trimString = function (string, length) {
      return string.length > length ? 
             string.substring(0, length) + '...' :
             string;
    };

사용 사례,

let string = 'How to trim a string to N chars in Javascript';

trimString(string, 20);

//How to trim a string...

선호하다String.prototype.slice에 걸쳐서String.prototype.substringmethod(서브스트링의 경우 예상과 다른 결과를 얻을 수 있습니다).

문자열을 왼쪽에서 오른쪽으로 트리밍합니다.

const str = "123456789";
result = str.slice(0,5);     // "12345", extracts first 5 characters
result = str.substring(0,5); // "12345"

startIndex > endIndex:

result = str.slice(5,0);     // "", empty string
result = str.substring(5,0); // "12345" , swaps start & end indexes => str.substring(0,5)

문자열을 오른쪽에서 왼쪽으로 트리밍합니다. (-ve start index)

result = str.slice(-3);                 // "789", extracts last 3 characters
result = str.substring(-3);             // "123456789" , -ve becomes 0 => str.substring(0)
result = str.substring(str.length - 3); // "789"

조금 늦게...난 대답을 해야 했다.이것이 가장 간단한 방법입니다.

// JavaScript
function fixedSize_JS(value, size) {
  return value.padEnd(size).substring(0, size);
}

// JavaScript (Alt)
var fixedSize_JSAlt = function(value, size) {
  return value.padEnd(size).substring(0, size);
}

// Prototype (preferred)
String.prototype.fixedSize = function(size) {
  return this.padEnd(size).substring(0, size);
}

// Overloaded Prototype
function fixedSize(value, size) {
  return value.fixedSize(size);
}

// usage
console.log('Old school JS -> "' + fixedSize_JS('test (30 characters)', 30) + '"');
console.log('Semi-Old school JS -> "' + fixedSize_JSAlt('test (10 characters)', 10) + '"');
console.log('Prototypes (Preferred) -> "' + 'test (25 characters)'.fixedSize(25) + '"');
console.log('Overloaded Prototype (Legacy support) -> "' + fixedSize('test (15 characters)', 15) + '"');

단계별. .padEnd - 문자열 길이를 나타냅니다.

padEnd() 메서드는 현재 스트링을 지정된 스트링(필요한 경우 반복)으로 패딩하여 결과 스트링이 지정된 길이에 도달하도록 합니다.패딩은 현재 문자열의 끝(오른쪽)부터 적용됩니다.이 대화형 예제의 소스는 GitHub 저장소에 저장됩니다." 출처: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/...

.secring - 필요한 길이로 제한

생략형을 추가할 경우 출력에 추가합니다.

일반적인 JavaScript 사용 예시를 4개 제시했습니다.레거시 지원을 위해 오버로드 기능이 있는 String 프로토타입을 사용할 것을 강력히 권장합니다.나중에 구현하고 변경하는 것이 훨씬 쉬워집니다.

다른 제안입니다. 후행 공백을 모두 제거합니다.

limitStrLength = (text, max_length) => {
    if(text.length > max_length - 3){
        return text.substring(0, max_length).trimEnd() + "..."
    }
    else{
        return text
    }

이를 실현하기 위한 몇 가지 방법이 있습니다.

let description = "your test description your test description your test description";
let finalDesc = shortMe(description, length);

function finalDesc(str, length){

// return str.slice(0,length);

// return str.substr(0, length);

// return str.substring(0, length);

}

문자열 사이에 삽입하도록 이 함수를 수정할 수도 있습니다.

이 코드를 사용하는 것이 좋을 것 같습니다:-)

    // sample string
            const param= "Hi you know anybody like pizaa";

         // You can change limit parameter(up to you)
         const checkTitle = (str, limit = 17) => {
      var newTitle = [];
      if (param.length >= limit) {
        param.split(" ").reduce((acc, cur) => {
          if (acc + cur.length <= limit) {
            newTitle.push(cur);
          }
          return acc + cur.length;
        }, 0);
        return `${newTitle.join(" ")} ...`;
      }
      return param;
    };
    console.log(checkTitle(str));

// result : Hi you know anybody ...

언급URL : https://stackoverflow.com/questions/7463658/how-to-trim-a-string-to-n-chars-in-javascript

반응형