Nice programing

현을 연결하는 방법이 있습니까?

nicepro 2020. 10. 24. 11:43
반응형

현을 연결하는 방법이 있습니까?


Javascript splice는 배열에서만 작동합니다. 비슷한 문자열 방법이 있습니까? 아니면 나만의 사용자 지정 함수를 만들어야합니까?

substr()substring()방법은 추출 된 문자열을 반환하고 원래 문자열을 수정하지 않습니다. 내가 원하는 것은 문자열에서 일부를 제거하고 변경 사항을 원래 문자열에 적용하는 것입니다. 또한 replace()인덱스에서 시작하여 다른 인덱스에서 끝나는 부분을 제거하고 싶기 때문에 메서드로 수행 할 수 있는 것과 똑같이이 메서드 가 작동하지 않습니다 splice(). 내 문자열을 배열로 변환하려고 시도했지만 이것은 깔끔한 방법이 아닙니다.


다음과 같이 문자열을 두 번 슬라이스하는 것이 더 빠릅니다.

function spliceSlice(str, index, count, add) {
  // We cannot pass negative indexes directly to the 2nd slicing operation.
  if (index < 0) {
    index = str.length + index;
    if (index < 0) {
      index = 0;
    }
  }

  return str.slice(0, index) + (add || "") + str.slice(index + count);
}

다음과 같이 분할 후 조인 (Kumar Harsh의 방법)을 사용하는 것보다

function spliceSplit(str, index, count, add) {
  var ar = str.split('');
  ar.splice(index, count, add);
  return ar.join('');
}

두 가지 방법과 다른 두 가지 방법을 비교 하는 jsperf 가 있습니다. (jsperf는 몇 달 동안 다운되었습니다. 의견에 대안을 제안하십시오.)

재현 구현 기능 위의 코드 있지만 일반 의 기능 splice아스카 제시 한 경우의 코드 최적화는 (즉, 변형 된 문자열에 아무것도 첨가되지 않은) 다양한 방법의 상대적 성능을 변경하지 않는다.


편집하다

이것은 물론 문자열을 "스플 라이스"하는 가장 좋은 방법은 아닙니다. 구현 방법에 대한 예제로 이것을 제공했습니다. 이것은 결함이 있고 split (), splice () 및 join ()에서 매우 분명합니다. 훨씬 더 나은 구현을 위해 Louis의 방법을 참조하십시오 .


아니요,와 같은 것은 String.splice없지만 다음을 시도해 볼 수 있습니다.

newStr = str.split(''); // or newStr = [...str];
newStr.splice(2,5);
newStr = newStr.join('');

splice배열에서와 같은 기능 이 없다는 것을 알고 있으므로 문자열을 배열로 변환해야합니다. 곤경...


다음은 더 나은 가독성 (IMHO)을 제공하는 멋진 작은 커리입니다.

두 번째 함수의 서명은 Array.prototype.splice방법 과 동일합니다 .

function mutate(s) {
    return function splice() {
        var a = s.split('');
        Array.prototype.splice.apply(a, arguments);
        return a.join('');
    };
}

mutate('101')(1, 1, '1');

이미 받아 들여진 답변이 있다는 것을 알고 있지만 이것이 유용하기를 바랍니다.


문자열에 substr사용하십시오.

전의.

var str = "Hello world!";
var res = str.substr(1, str.length);

결과 = ello world!


elclanrs 및 raina77ow의 의견에서만 해결 된 많은 혼란이있는 것 같으므로 명확한 답변을 게시하겠습니다.

설명

" string.splice"에서 다음과 같이 예상 할 수 있습니다.

  • 최대 3 개의 인수 허용 : 시작 위치, 길이 및 (선택 사항) 삽입 (문자열)
  • 잘라낸 부분을 반환
  • 원래 문자열을 수정합니다.

문제는 문자열이 변경 불가능하기 때문에 3d 요구 사항을 충족 할 수 없다는 것입니다 (관련 : 1 , 2 ). 여기서 가장 헌신적 인 주석을 찾았습니다 .

JavaScript에서 문자열은 객체가 아닌 원시 값 유형입니다 ( spec ). 사실, ES5의, 그들은 나란히 5 값 유형 중 하나를있어 null, undefined, numberboolean. 문자열에 의해 할당 된 하지 참조 등으로 전달된다. 따라서 문자열은 불변 일뿐만 아니라 입니다. 문자열 "hello"바꾸는 것은 "world"지금부터 숫자 3이 숫자 4라고 결정하는 것과 같습니다.

따라서이를 고려하여 " string.splice"항목은 다음과 같은 경우에만 예상 할 수 있습니다 .

  • 최대 2 개의 인수 허용 : 시작 위치, 길이 (문자열이 변경되지 않았으므로 삽입이 의미가 없음)
  • 잘라낸 부분을 반환

그것이 무엇을 하는가 substr; 또는,

  • 최대 3 개의 인수 허용 : 시작 위치, 길이 및 (선택 사항) 삽입 (문자열)
  • 수정 된 문자열을 반환합니다 (절단 부분 제외 및 삽입 포함)

다음 섹션의 주제입니다.

솔루션

최적화에 관심이 있다면 Mike의 구현을 사용해야 할 것입니다.

String.prototype.splice = function(index, count, add) {
    if (index < 0) {
        index += this.length;
        if (index < 0)
            index = 0;
    }
    return this.slice(0, index) + (add || "") + this.slice(index + count);
}

하지만 경계를 벗어난 인덱스를 처리하는 방법은 다를 수 있습니다. 필요에 따라 다음을 원할 수 있습니다.

    if (index < 0) {
        index += this.length;
        if (index < 0)
            index = 0;
    }
    if (index >= this.length) {
        index -= this.length;
        if (index >= this.length)
            index = this.length - 1;
    }

또는

    index = index % this.length;
    if (index < 0)
        index = this.length + index;

성능에 신경 쓰지 않는다면 Kumar의 제안을보다 간단하게 적용 할 수 있습니다.

String.prototype.splice = function(index, count, add) {
    var chars = this.split('');
    chars.splice(index, count, add);
    return chars.join('');
}

공연

The difference in performances increases drastically with the length of the string. jsperf shows, that for strings with the length of 10 the latter solution (splitting & joining) is twice slower than the former solution (using slice), for 100-letter strings it's x5 and for 1000-letter strings it's x50, in Ops/sec it's:

                      10 letters   100 letters   1000 letters
slice implementation    1.25 M       2.00 M         1.91 M
split implementation    0.63 M       0.22 M         0.04 M

note that I've changed the 1st and 2d arguments when moving from 10 letters to 100 letters (still I'm surprised that the test for 100 letters runs faster than that for 10 letters).


I would like to offer a simpler alternative to both the Kumar/Cody and the Louis methods. On all the tests I ran, it performs as fast as the Louis method (see fiddle tests for benchmarks).

String.prototype.splice = function(startIndex,length,insertString){
    return this.substring(0,startIndex) + insertString + this.substring(startIndex + length);
};

You can use it like this:

var creditCardNumber = "5500000000000004";
var cardSuffix = creditCardNumber.splice(0,12,'****');
console.log(cardSuffix);  // output: ****0004

See Test Results: https://jsfiddle.net/0quz9q9m/5/


The method Louis's answer, as a String prototype function:

String.prototype.splice = function(index, count, add) {
  if (index < 0) {
    index = this.length + index;
    if (index < 0) {
      index = 0;
    }
  }
  return this.slice(0, index) + (add || "") + this.slice(index + count);
}

Example:

 > "Held!".splice(3,0,"lo Worl")
 < "Hello World!"

So, whatever adding splice method to a String prototype cant work transparent to spec...

Let's do some one extend it:

String.prototype.splice = function(...a){
    for(var r = '', p = 0, i = 1; i < a.length; i+=3)
        r+= this.slice(p, p=a[i-1]) + (a[i+1]||'') + this.slice(p+a[i], p=a[i+2]||this.length);
    return r;
}
  • Every 3 args group "inserting" in splice style.
  • Special if there is more then one 3 args group, the end off each cut will be the start of next.
    • '0123456789'.splice(4,1,'fourth',8,1,'eighth'); //return '0123fourth567eighth9'
  • You can drop or zeroing the last arg in each group (that treated as "nothing to insert")
    • '0123456789'.splice(-4,2); //return '0123459'
  • You can drop all except 1st arg in last group (that treated as "cut all after 1st arg position")
    • '0123456789'.splice(0,2,null,3,1,null,5,2,'/',8); //return '24/7'
  • if You pass multiple, you MUST check the sort of the positions left-to-right order by youreself!
  • And if you dont want you MUST DO NOT use it like this:
    • '0123456789'.splice(4,-3,'what?'); //return "0123what?123456789"

참고URL : https://stackoverflow.com/questions/20817618/is-there-a-splice-method-for-strings

반응형