Programing

모든 문자열을 바꾸는 방법은 무엇입니까?

lottogame 2020. 11. 19. 07:44
반응형

모든 문자열을 바꾸는 방법은 무엇입니까?


이 문자열이 있습니다.

"Test abc test test abc test test test abc test test abc"

하기:

str = str.replace('abc', '');

abc위의 문자열에서 첫 번째 항목 만 제거하는 것 같습니다 .

모든 항목을 어떻게 바꿀 수 있습니까?


완전성을 위해이 작업을 수행하는 데 어떤 방법을 사용해야하는지 생각해야했습니다. 이 페이지의 다른 답변에서 제안한 것처럼 기본적으로 두 가지 방법이 있습니다.

참고 : 일반적으로 JavaScript에서 내장 프로토 타입을 확장하는 것은 일반적으로 권장되지 않습니다. 기본 제공 프로토 타입에서 가상 표준 메서드의 다양한 구현을 보여주기 위해 단순히 설명을 위해 String 프로토 타입에 대한 확장을 제공하고 있습니다 String.


정규식 기반 구현

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};

분할 및 결합 (기능적) 구현

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.split(search).join(replacement);
};

효율성 측면에서 정규 표현식이 배후에서 작동하는 방식에 대해 너무 많이 알지 못해 과거에는 성능에 대해 생각하지 않고 분할 및 조인 구현에 의지하는 경향이있었습니다. 어느 것이 더 효율적이고 어느 정도인지 궁금했을 때 나는 그것을 알아 내기위한 핑계로 사용했습니다.

내 크롬 윈도우 8 시스템에서, 정규 표현식 기반 구현이 가장 빠른 으로, 분할 및 구현 53 % 느리게되고 가입 . 정규 표현식이 내가 사용한 lorem ipsum 입력보다 두 배 빠르다는 것을 의미합니다.

이 두 가지 구현을 서로에 대해 실행 하는이 벤치 마크를 확인하십시오 .


@ThomasLeduc 등의 아래 주석에서 언급했듯이 정규 표현식 에서 특수 문자로search 예약 된 특정 문자가 포함 된 경우 정규 표현식 기반 구현에 문제가있을 수 있습니다 . 구현에서는 호출자가 문자열을 미리 이스케이프하거나 정규식 (MDN) 의 테이블에있는 문자가없는 문자열 만 전달한다고 가정합니다 .

MDN은 또한 문자열을 이스케이프하는 구현을 제공합니다. 이것도으로 표준화되어 있으면 좋겠지 RegExp.escape(str)만 아쉽게도 존재하지 않습니다.

function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}

구현 escapeRegExp내에서 호출 할 수 String.prototype.replaceAll있지만 이것이 성능에 얼마나 영향을 미치는지 확실하지 않습니다 (모든 영숫자 문자열처럼 이스케이프가 필요하지 않은 문자열의 경우에도 가능).


str = str.replace(/abc/g, '');

의견에 대한 답변 :

var find = 'abc';
var re = new RegExp(find, 'g');

str = str.replace(re, '');

Click Upvote 의 댓글에 대한 응답으로 더 단순화 할 수 있습니다.

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(find, 'g'), replace);
}

참고 : 정규식에는 특수 (메타) 문자가 포함되어 있으므로 find해당 문자를 이스케이프하기 위해 사전 처리하지 않고 위 함수 에서 인수를 맹목적으로 전달하는 것은 위험합니다 . 이 내용은 Mozilla Developer Network정규 표현식에 대한 JavaScript 가이드에서 다룹니다 . 여기에서 다음 유틸리티 함수를 제공합니다.

function escapeRegExp(str) {
    return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

따라서 replaceAll()기능을 더 안전하게 만들기 위해 다음을 포함하면 다음과 같이 수정할 수 있습니다 escapeRegExp.

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

참고 : 실제 코드에서는 사용하지 마십시오.

간단한 리터럴 문자열에 대한 정규식의 대안으로 다음을 사용할 수 있습니다.

str = "Test abc test test abc test...".split("abc").join("");

일반적인 패턴은

str.split(search).join(replacement)

이것은 일부 경우 replaceAll에 정규식을 사용하는 것보다 더 빠르지 만 최신 브라우저에서는 더 이상 그렇지 않은 것 같습니다. 따라서 이것은 실제 코드가 아닌 정규 표현식을 이스케이프 할 필요가 없도록 빠른 해킹으로 만 사용해야합니다.


g플래그가 설정된 정규식을 사용하면 다음을 모두 대체합니다.

someString = 'the cat looks like a cat';
anotherString = someString.replace(/cat/g, 'dog');
// anotherString now contains "the dog looks like a dog"

여기도 참조


다음은 허용 된 답변을 기반으로 한 문자열 프로토 타입 함수입니다.

String.prototype.replaceAll = function (find, replace) {
    var str = this;
    return str.replace(new RegExp(find, 'g'), replace);
};

편집하다

find특수 문자가 포함 된 경우 이스케이프해야합니다.

String.prototype.replaceAll = function (find, replace) {
    var str = this;
    return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};

바이올린 : http://jsfiddle.net/cdbzL/


최신 정보:

업데이트가 다소 늦었지만 방금이 질문을 우연히 발견하고 이전 답변이 만족스럽지 않다는 것을 알았습니다. 한 단어를 바꾸는 문제가 있었기 때문에 아무도 단어 경계를 사용하는 것을 생각하지 않았다는 것이 놀랍습니다 ( \b)

'a cat is not a caterpillar'.replace(/\bcat\b/gi,'dog');
//"a dog is not a caterpillar"

이것은 대부분의 경우 단어의 일부를 바꾸지 않는 간단한 정규식입니다. 그러나 대시 -는 여전히 단어 경계로 간주됩니다. 따라서이 경우 조건문을 사용하여 다음과 같은 문자열을 대체하지 않을 수 있습니다 cool-cat.

'a cat is not a cool-cat'.replace(/\bcat\b/gi,'dog');//wrong
//"a dog is not a cool-dog" -- nips
'a cat is not a cool-cat'.replace(/(?:\b([^-]))cat(?:\b([^-]))/gi,'$1dog$2');
//"a dog is not a cool-cat"

기본적으로이 질문은 여기에있는 질문과 동일합니다. Javascript는 " '"를 "' '"로 대체 합니다.

@Mike, 내가 거기에 준 대답을 확인하십시오 ... regexp는 subsrting의 여러 발생을 대체하는 유일한 방법이 아닙니다. 유연하게 생각하고 분할을 생각하십시오!

var newText = "the cat looks like a cat".split('cat').join('dog');

또는 승인 된 답변으로도 할 수있는 단어 부분 교체를 방지합니다! 내가 인정하는 정규 표현식을 사용하면이 문제를 해결할 수 있습니다. 좀 더 복잡하고 그 결과로도 약간 느립니다.

var regText = "the cat looks like a cat".replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");

출력은 허용 된 답변과 동일하지만 다음 문자열에 / cat / g 표현식을 사용합니다.

var oops = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/cat/g,'dog');
//returns "the dog looks like a dog, not a dogerpillar or cooldog" ?? 

죄송합니다. 이것은 아마도 당신이 원하는 것이 아닐 것입니다. 그럼 뭐야? IMHO, 조건부로 '고양이'만 대체하는 정규식입니다. (즉, 단어의 일부가 아님) 다음과 같이 :

var caterpillar = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");
//return "the dog looks like a dog, not a caterpillar or coolcat"

제 생각에는 이것이 귀하의 요구를 충족시키는 것입니다. 물론 완벽하지는 않지만 시작하기에 충분할 것입니다. 이 페이지에서 더 많은 것을 읽는 것이 좋습니다. 이것은 당신의 특정한 필요를 충족시키기 위해이 표현을 완성하는 데 유용 할 것입니다.

http://www.javascriptkit.com/jsref/regexp.shtml

http://www.regular-expressions.info


최종 추가 :

이 질문이 여전히 많은 뷰를 얻는 것을 감안할 때 .replace콜백 함수와 함께 사용되는 예제를 추가 할 수 있다고 생각했습니다 . 이 경우, 극적으로 표현을 단순화 하고 올바른 대문자로 교체 또는 둘 모두를 교체처럼, 더 많은 유연성을 제공 cat하고 cats하나의 이동에 :

'Two cats are not 1 Cat! They\'re just cool-cats, you caterpillar'
   .replace(/(^|.\b)(cat)(s?\b.|$)/gi,function(all,char1,cat,char2)
    {
       //check 1st, capitalize if required
       var replacement = (cat.charAt(0) === 'C' ? 'D' : 'd') + 'og';
       if (char1 === ' ' && char2 === 's')
       {//replace plurals, too
           cat = replacement + 's';
       }
       else
       {//do not replace if dashes are matched
           cat = char1 === '-' || char2 === '-' ? cat : replacement;
       }
       return char1 + cat + char2;//return replacement string
    });
//returns:
//Two dogs are not 1 Dog! They're just cool-cats, you caterpillar

전역 정규식과 일치 :

anotherString = someString.replace(/cat/g, 'dog');

가장 일반적이고 읽기 쉬운 방법입니다.

var str = "Test abc test test abc test test test abc test test abc"

방법 -01 :

str = str.replace(/abc/g, "replaced text");

방법 -02 :

str = str.split("abc").join("replaced text");

방법 -03 :

str = str.replace(new RegExp("abc", "g"), "replaced text");

방법 -04 :

while(str.includes("abc")){
    str = str.replace("abc", "replaced text");
}

산출:

console.log(str);
// Test replaced text test test replaced text test test test replaced text test test replaced text

1 회용 교체 용 :

var res = str.replace('abc', "");

여러 번 교체하려면 다음을 사용하십시오.

var res = str.replace(/abc/g, "");

str = str.replace(/abc/g, '');

또는 여기에서 replaceAll 기능을 시도하십시오.

내장 객체를 확장하는 유용한 JavaScript 메소드는 무엇입니까?

str = str.replaceAll('abc', ''); OR

var search = 'abc';
str = str.replaceAll(search, '');

편집 : replaceAll 가용성에 대한 설명

'replaceAll'메소드가 String의 프로토 타입에 추가되었습니다. 이것은 모든 문자열 객체 / 리터럴에 사용할 수 있음을 의미합니다.

var output = "test this".replaceAll('this', 'that');  //output is 'test that'.
output = output.replaceAll('that', 'this'); //output is 'test this'

모든 'abc'를 'x'로 바꾸고 싶다고 가정 해 보겠습니다.

let some_str = 'abc def def lom abc abc def'.split('abc').join('x')
console.log(some_str) //x def def lom x x def

문자열 프로토 타입을 수정하는 것보다 더 간단한 것을 생각하려고했습니다.


정규식을 사용하십시오.

str.replace(/abc/g, '');

작은 따옴표 바꾸기 :

function JavaScriptEncode(text){
    text = text.replace(/'/g,''')
    // More encode here if required

    return text;
}

사용 RegExp자바 스크립트를 잊지 마세요, 단지 다음과 같은 일을 할, 당신을 위해 일을 할 수있는 /g에있는 뛰어난 이후 글로벌 :

var str ="Test abc test test abc test test test abc test test abc";
str = str.replace(/abc/g, '');

재사용을 생각한다면이를위한 함수를 만드세요.하지만 한 줄 함수일 뿐이므로 권장하지 않지만, 이것을 많이 사용한다면 다음과 같이 작성할 수 있습니다.

String.prototype.replaceAll = String.prototype.replaceAll || function(string, replaced) {
  return this.replace(new RegExp(string, 'g'), replaced);
};

다음과 같이 코드에서 계속해서 사용하십시오.

var str ="Test abc test test abc test test test abc test test abc";
str = str.replaceAll('abc', '');

그러나 앞서 언급했듯이 작성되는 줄이나 성능 측면에서 큰 차이를 만들지는 않을 것입니다. 함수를 캐싱하는 것만으로 긴 문자열에서 더 빠른 성능에 영향을 미칠 수 있으며 재사용하려는 경우 DRY 코드의 좋은 사례도 있습니다.


이것은이다 빠른 버전의 정규 표현식을 사용하지 않습니다 .

jsperf 수정

replaceAll = function(string, omit, place, prevstring) {
  if (prevstring && string === prevstring)
    return string;
  prevstring = string.replace(omit, place);
  return replaceAll(prevstring, omit, place, string)
}

분할 및 결합 방법 보다 거의 두 배 빠릅니다.

여기 주석에서 지적했듯이 omit변수에 place,에서와 같이 포함되어 있으면 작동하지 않습니다 . replaceAll("string", "s", "ss")왜냐하면 항상 다른 단어를 대체 할 수 있기 때문입니다.

내 재귀 교체에 변형이있는 또 다른 jsperf가 더 빠르게 진행됩니다 ( http://jsperf.com/replace-all-vs-split-join/12 )!

  • 2017 년 7 월 27 일 업데이트 : RegExp가 최근 출시 된 Chrome 59에서 가장 빠른 성능을 제공하는 것 같습니다.

// 횟수가 0이 될 때까지 반복합니다. 또는 간단히 복사 / 붙여 넣기

    function replaceAll(find, replace, str) 
    {
      while( str.indexOf(find) > -1)
      {
        str = str.replace(find, replace);
      }
      return str;
    }

str = str.replace(new RegExp("abc", 'g'), "");

worked better for me than the above answers. so new RegExp("abc", 'g') creates a RegExp what matches all occurence ('g' flag) of the text ("abc"). The second part is what gets replaced to, in your case empty string (""). str is the string, and we have to override it, as replace(...) just returns result, but not overrides. In some cases you might want to use that.


If what you want to find is already in a string, and you don't have a regex escaper handy, you can use join/split:

    function replaceMulti(haystack, needle, replacement)
    {
        return haystack.split(needle).join(replacement);
    }

    someString = 'the cat looks like a cat';
    console.log(replaceMulti(someString, 'cat', 'dog'));


function replaceAll(str, find, replace) {
  var i = str.indexOf(find);
  if (i > -1){
    str = str.replace(find, replace); 
    i = i + replace.length;
    var st2 = str.substring(i);
    if(st2.indexOf(find) > -1){
      str = str.substring(0,i) + replaceAll(st2, find, replace);
    }       
  }
  return str;
}

I like this method (it looks a little cleaner):

text = text.replace(new RegExp("cat","g"), "dog"); 

var str = "ff ff f f a de def";
str = str.replace(/f/g,'');
alert(str);

http://jsfiddle.net/ANHR9/


while (str.indexOf('abc') !== -1)
{
    str = str.replace('abc', '');
}

If the string contain similar pattern like abccc, you can use this:

str.replace(/abc(\s|$)/g, "")

The previous answers are way too complicated. Just use the replace function like this:

str.replace(/your_regex_pattern/g, replacement_string);

Example:

var str = "Test abc test test abc test test test abc test test abc";

var res = str.replace(/[abc]+/g, "");

console.log(res);


The simplest way to this without using any regex is split and join like code here :

var str="Test abc test test abc test test test abc test test abc";
str.split('abc').join('')

If you are trying to ensure that the string you are looking for won't exist even after the replacement, you need to use a loop.

For example:

var str = 'test aabcbc';
str = str.replace(/abc/g, '');

When complete, you will still have 'test abc'!

The simplest loop to solve this would be:

var str = 'test aabcbc';
while (str != str.replace(/abc/g, '')){
   str.replace(/abc/g, '');
}

But that runs the replacement twice for each cycle. Perhaps (at risk of being voted down) that can be combined for a slightly more efficient but less readable form:

var str = 'test aabcbc';
while (str != (str = str.replace(/abc/g, ''))){}
// alert(str); alerts 'test '!

This can be particularly useful when looking for duplicate strings.
For example, if we have 'a,,,b' and we wish to remove all duplicate commas.
[In that case, one could do .replace(/,+/g,','), but at some point the regex gets complex and slow enough to loop instead.]


Although people have mentioned the use of regex but there's a better approach if you want to replace the text irrespective of the case of the text. Like uppercase or lowercase. Use below syntax

//Consider below example
originalString.replace(/stringToBeReplaced/gi, '');

//Output will be all the occurrences removed irrespective of casing.

You can refer the detailed example here.


Just add /g

document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');

to

// Replace 'hello' string with /hello/g regular expression.
document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi');

/g means global


I have solved this problem by a simple line of code.

str.replace(/Current string/g, "Replaced string");

Check example on jsfiddle https://jsfiddle.net/pot6whnx/1/


You can simply use below method

/**
 * Replace all the occerencess of $find by $replace in $originalString
 * @param  {originalString} input - Raw string.
 * @param  {find} input - Target key word or regex that need to be replaced.
 * @param  {replace} input - Replacement key word
 * @return {String}       Output string
 */
function replaceAll(originalString, find, replace) {
  return originalString.replace(new RegExp(find, 'g'), replace);
};

참고URL : https://stackoverflow.com/questions/832257/javascript-multiple-replace

반응형