source

특정 인덱스에 문자열 삽입

goodcode 2022. 9. 11. 17:15
반응형

특정 인덱스에 문자열 삽입

다른 문자열의 특정 인덱스에 문자열을 삽입하려면 어떻게 해야 합니까?

 var txt1 = "foo baz"

foo 뒤에 bar를 삽입하려면 어떻게 해야 하나요?

substring()이데올로기 때문에

(예를 들어 첫 번째 공백 문자가 아닌) 특정 인덱스에 삽입하려면 문자열 슬라이스/서브스트링을 사용해야 합니다.

var txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);

할 수 있습니다.splice()문자열로 변환합니다.

폴리필

if (!String.prototype.splice) {
    /**
     * {JSDoc}
     *
     * The splice() method changes the content of a string by removing a range of
     * characters and/or adding new characters.
     *
     * @this {String}
     * @param {number} start Index at which to start changing the string.
     * @param {number} delCount An integer indicating the number of old chars to remove.
     * @param {string} newSubStr The String that is spliced in.
     * @return {string} A new string with the spliced substring.
     */
    String.prototype.splice = function(start, delCount, newSubStr) {
        return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
    };
}

String.prototype.splice = function(idx, rem, str) {
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};

var result = "foo baz".splice(4, 0, "bar ");

document.body.innerHTML = result; // "foo bar baz"


편집: 수정하여rem을 사용하다

다음은 다른 모든 프로그래밍 언어와 동일하게 동작하는 방법입니다.

String.prototype.insert = function(index, string) {
  if (index > 0) {
    return this.substring(0, index) + string + this.substr(index);
  }

  return string + this;
};

//Example of use:
var something = "How you?";
something = something.insert(3, " are");
console.log(something)

레퍼런스:

다음과 같은 기능만 만드십시오.

function insert(str, index, value) {
    return str.substr(0, index) + value + str.substr(index);
}

이렇게 사용해요.

alert(insert("foo baz", 4, "bar "));

출력: foo bar baz

C#(Sharp) 문자열과 동일하게 동작합니다.삽입(int start)인덱스, 문자열 값).

메모: 이 삽입 함수는 문자열 str(첫 번째 매개 변수)에 지정된 정수 인덱스(두 번째 매개 변수) 에 문자열 값(세 번째 매개 변수)을 삽입한 후 str을 변경하지 않고 새 문자열을 반환합니다.

UPDATE 2016: 원라이너 접근 방식(프리펜드 지원 포함)을 기반으로 한 또 다른 Just for Fun(단, 더 심각한) 프로토타입 기능이 있습니다.undefined 마이너스(negative)입니다.index

/**
 * Insert `what` to string at position `index`.
 */
String.prototype.insert = function(what, index) {
    return index > 0
        ? this.replace(new RegExp('.{' + index + '}'), '$&' + what)
        : what + this;
};

console.log( 'foo baz'.insert('bar ', 4) );  // "foo bar baz"
console.log( 'foo baz'.insert('bar ')    );  // "bar foo baz"

이전(2012년 이전)의 재미 솔루션:

var index = 4,
    what  = 'bar ';

'foo baz'.replace(/./g, function(v, i) {
    return i === index - 1 ? v + what : v;
});  // "foo bar baz"

이것은 기본적으로 @Base33이 하고 있는 것을 나타내고 있습니다.단, 음의 인덱스를 사용하여 끝에서 카운트하는 옵션도 제공하고 있습니다.기판법이 허용하는 것과 비슷합니다.

// use a negative index to insert relative to the end of the string.

String.prototype.insert = function (index, string) {
  var ind = index < 0 ? this.length + index  :  index;
  return  this.substring(0, ind) + string + this.substr(ind);
};

예:명명 규칙을 사용하는 풀사이즈 이미지가 있지만 썸네일 URL을 제공하도록 데이터를 업데이트할 수 없다고 가정해 보겠습니다.

var url = '/images/myimage.jpg';
var thumb = url.insert(-4, '_thm');

//    result:  '/images/myimage_thm.jpg'

문자열의 여러 인덱스에 텍스트를 삽입하는 방법을 찾는 사용자가 있다면 다음을 시도해 보십시오.

String.prototype.insertTextAtIndices = function(text) {
    return this.replace(/./g, function(character, index) {
        return text[index] ? text[index] + character : character;
    });
};

를 들어, 이 하여 " ", "를 삽입할 수 .<span>문자열의 특정 오프셋에서 태그:

var text = {
    6: "<span>",
    11: "</span>"
};

"Hello world!".insertTextAtIndices(text); // returns "Hello <span>world</span>!"
  1. 문자열에서 어레이 인스턴스화
  2. 어레이 #스플라이스 사용
  3. Array #join을 사용하여 다시 문자열 지정

이 접근방식의 이점은 두 가지입니다.

  1. 간단하죠.
  2. Unicode 코드 포인트 준수

const pair = Array.from('USDGBP')
pair.splice(3, 0, '/')
console.log(pair.join(''))

현재의 예에서는, 다음의 어느쪽인가를 사용해 결과를 얻을 수 있습니다.

var txt2 = txt1.split(' ').join(' bar ')

또는

var txt2 = txt1.replace(' ', ' bar ');

하지만 당신이 그런 가정을 할 수 있다면, 당신은 Gulen의 예로 바로 건너뛸 수 있습니다.

문자 인덱스를 기반으로 하는 것 이외에는 어떠한 추측도 할 수 없는 상황이라면, 저는 정말로 서브스트링 솔루션을 선택하겠습니다.

my_string          = "hello world";
my_insert          = " dear";
my_insert_location = 5;

my_string = my_string.split('');  
my_string.splice( my_insert_location , 0, my_insert );
my_string = my_string.join('');

https://jsfiddle.net/gaby_de_wilde/wz69nw9k/

이것이 오래된 줄거리라는 것을 알지만, 여기 정말 효과적인 방법이 있습니다.

var tn = document.createTextNode("I am just  to help")
t.insertData(10, "trying");

이 방법의 장점은 노드 내용을 강제한다는 것입니다.따라서 이 노드가 이미 DOM에 있는 경우 쿼리 선택기를 사용하거나 innerText를 업데이트할 필요가 없습니다.변경은 구속력 때문에 반영될 것이다.

문자열이 필요한 경우 노드의 텍스트 컨텐츠 속성에 액세스하기만 하면 됩니다.

tn.textContent
#=> "I am just trying to help"

코드 한 줄에 regexp를 사용하면 쉽게 할 수 있습니다.

const str = 'Hello RegExp!';
const index = 6;
const insert = 'Lovely ';
    
//'Hello RegExp!'.replace(/^(.{6})(.)/, `$1Lovely $2`);
const res = str.replace(new RegExp(`^(.{${index}})(.)`), `$1${insert}$2`);
    
console.log(res);

"안녕하세요 Lovely RegExp!"

서브스트링과 슬라이스 방법을 모두 사용할 수 있습니다.

String.prototype.customSplice = function (index, absIndex, string) {
    return this.slice(0, index) + string+ this.slice(index + Math.abs(absIndex));
};


String.prototype.replaceString = function (index, string) {
    if (index > 0)
        return this.substring(0, index) + string + this.substr(index);

    return string + this;
};


console.log('Hello Developers'.customSplice(6,0,'Stack ')) // Hello Stack Developers
console.log('Hello Developers'.replaceString(6,'Stack ')) //// Hello Stack Developers

서브스트링 방식의 유일한 문제는 음의 지수에서는 작동하지 않는다는 것입니다.항상 0번째 위치에서 문자열 인덱스를 가져옵니다.

동적 패턴과 함께 정규 표현을 사용할 수 있습니다.

var text = "something";
var output = "                    ";
var pattern = new RegExp("^\\s{"+text.length+"}");
var output.replace(pattern,text);

출력:

"something      "

이것이 대체됩니다.text.length문자열의 선두에 있는 공백 문자의output.그RegExp수단^\- 행의 시작\s임의의 공백 문자, 반복{n}횟수(이 경우)text.length.사용하다\\로.\끈으로 이런 패턴을 만들 때 백슬래시를 탈출할 수 있습니다.

다른 용액으로 끈을 2등분하고 그 사이에 끈을 끼운다.

var str = jQuery('#selector').text();

var strlength = str.length;

strf = str.substr(0 , strlength - 5);
strb = str.substr(strlength - 5 , 5);

jQuery('#selector').html(strf + 'inserted' + strb);

슬라이스 사용

사용할 수 있습니다.slice(0,index) + str + slice(index)또는 메서드를 만들 수도 있습니다.

String.prototype.insertAt = function(index,str){
  return this.slice(0,index) + str + this.slice(index)
}
console.log("foo bar".insertAt(4,'baz ')) //foo baz bar

문자열의 스플라이스 방식

넌 할 수 있다.split()메인 스트링과 추가 후 normal을 사용합니다.splice()

String.prototype.splice = function(index,del,...newStrs){
  let str = this.split('');
  str.splice(index,del,newStrs.join('') || '');
  return str.join('');
}


 var txt1 = "foo baz"

//inserting single string.
console.log(txt1.splice(4,0,"bar ")); //foo bar baz


//inserting multiple strings
console.log(txt1.splice(4,0,"bar ","bar2 ")); //foo bar bar2 baz


//removing letters
console.log(txt1.splice(1,2)) //f baz


//remving and inseting atm
console.log(txt1.splice(1,2," bar")) //f bar baz

여러 인덱스에서 splice() 적용

이 메서드는 어레이의 각 요소를 하나의 어레이로 나타냅니다.splice().

String.prototype.splice = function(index,del,...newStrs){
  let str = this.split('');
  str.splice(index,del,newStrs.join('') || '');
  return str.join('');
}


String.prototype.mulSplice = function(arr){
  str = this
  let dif = 0;
  
  arr.forEach(x => {
    x[2] === x[2] || [];
    x[1] === x[1] || 0;
    str = str.splice(x[0] + dif,x[1],...x[2]);
    dif += x[2].join('').length - x[1];
  })
  return str;
}

let txt = "foo bar baz"

//Replacing the 'foo' and 'bar' with 'something1' ,'another'
console.log(txt.splice(0,3,'something'))
console.log(txt.mulSplice(
[
[0,3,["something1"]],
[4,3,["another"]]
]

))

해결 방법을 선택하라.이 코드를 쉬운 형식으로 작성했습니다.

const insertWord = (sentence,word,index) => {
    var sliceWord = word.slice(""),output = [],join; // Slicing the input word and declaring other variables
    var sliceSentence = sentence.slice(""); // Slicing the input sentence into each alphabets
    for (var i = 0; i < sliceSentence.length; i++) 
           {
        if (i === index) 
               { // checking if index of array === input index
            for (var j = 0; j < word.length; j++) 
                       {   // if yes we'll insert the word
                output.push(sliceWord[j]); // Condition is true we are inserting the word
                       }
            output.push(" "); // providing a single space at the end of the word
                 }
        output.push(sliceSentence[i]);  // pushing the remaining elements present in an array
            }
    join = output.join(""); // converting an array to string
    console.log(join)
    return join;
}

Base33과 user113716에서 서브스트링을 사용한 메서드와 슬라이스를 사용한 메서드를 비교하여 코드를 작성했습니다.

퍼포먼스 비교, 서브스트링, 슬라이스도 참조해 주세요.

내가 사용한 코드는 큰 문자열을 만들고 큰 문자열에 "bar" 문자열을 여러 번 삽입합니다.

if (!String.prototype.splice) {
    /**
     * {JSDoc}
     *
     * The splice() method changes the content of a string by removing a range of
     * characters and/or adding new characters.
     *
     * @this {String}
     * @param {number} start Index at which to start changing the string.
     * @param {number} delCount An integer indicating the number of old chars to remove.
     * @param {string} newSubStr The String that is spliced in.
     * @return {string} A new string with the spliced substring.
     */
    String.prototype.splice = function (start, delCount, newSubStr) {
        return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
    };
}

String.prototype.splice = function (idx, rem, str) {
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};


String.prototype.insert = function (index, string) {
    if (index > 0)
        return this.substring(0, index) + string + this.substring(index, this.length);

    return string + this;
};


function createString(size) {
    var s = ""
    for (var i = 0; i < size; i++) {
        s += "Some String "
    }
    return s
}


function testSubStringPerformance(str, times) {
    for (var i = 0; i < times; i++)
        str.insert(4, "bar ")
}

function testSpliceStringPerformance(str, times) {
    for (var i = 0; i < times; i++)
        str.splice(4, 0, "bar ")
}


function doTests(repeatMax, sSizeMax) {
    n = 1000
    sSize = 1000
    for (var i = 1; i <= repeatMax; i++) {
        var repeatTimes = n * (10 * i)
        for (var j = 1; j <= sSizeMax; j++) {
            var actualStringSize = sSize *  (10 * j)
            var s1 = createString(actualStringSize)
            var s2 = createString(actualStringSize)
            var start = performance.now()
            testSubStringPerformance(s1, repeatTimes)
            var end = performance.now()
            var subStrPerf = end - start

            start = performance.now()
            testSpliceStringPerformance(s2, repeatTimes)
            end = performance.now()
            var splicePerf = end - start

            console.log(
                "string size           =", "Some String ".length * actualStringSize, "\n",
                "repeat count          = ", repeatTimes, "\n",
                "splice performance    = ", splicePerf, "\n",
                "substring performance = ", subStrPerf, "\n",
                "difference = ", splicePerf - subStrPerf  // + = splice is faster, - = subStr is faster
                )

        }
    }
}

doTests(1, 100)

성능의 일반적인 차이는 기껏해야 미미하며 두 방법 모두 잘 작동합니다(길이의 문자열에서도 ~12000000).

언급URL : https://stackoverflow.com/questions/4313841/insert-a-string-at-a-specific-index

반응형