Programing

JavaScript에서 텍스트를 바꾸어 JavaScript에서 str_replace를 수행하려면 어떻게해야합니까?

lottogame 2020. 6. 27. 10:57
반응형

JavaScript에서 텍스트를 바꾸어 JavaScript에서 str_replace를 수행하려면 어떻게해야합니까?


str_replaceJavaScript의 일부 텍스트를 대체 하기 위해 또는 이와 유사한 대안 을 사용하고 싶습니다 .

var text = "this is some sample text that i want to replace";
var new_text = replace_in_javascript("want", "dont want", text);
document.write("new_text");

주어야한다

this is some sample text that i dont want to replace

정규식을 사용하려는 경우 내장 대체 방법과 비교하여 성능에 미치는 영향은 무엇입니까?


문자열 교체에 정규식을 사용하면 문자열 교체를 사용하는 것보다 속도가 훨씬 느립니다. JSPerf 에서
설명 했듯이 정규 표현식을 만드는 데 다른 수준의 효율성을 가질 수 있지만 모든 것이 간단한 문자열 바꾸기보다 훨씬 느립니다. 다음과 같은 이유로 정규 표현식이 느려집니다 .

고정 문자열 일치에는 역 추적, 컴파일 단계, 범위, 문자 클래스 또는 정규식 엔진 속도를 늦추는 여러 가지 기능이 없습니다. 정규 표현식 일치를 최적화하는 방법은 확실히 있지만 일반적인 경우에는 색인을 문자열로 이길 가능성이 낮습니다.

JS perf 페이지에서 간단한 테스트 실행을 위해 몇 가지 결과를 문서화했습니다.

<script>
// Setup
  var startString = "xxxxxxxxxabcxxxxxxabcxx";
  var endStringRegEx = undefined;
  var endStringString = undefined;
  var endStringRegExNewStr = undefined;
  var endStringRegExNew = undefined;
  var endStringStoredRegEx = undefined;      
  var re = new RegExp("abc", "g");
</script>

<script>
// Tests
  endStringRegEx = startString.replace(/abc/g, "def") // Regex
  endStringString = startString.replace("abc", "def", "g") // String
  endStringRegExNewStr = startString.replace(new RegExp("abc", "g"), "def"); // New Regex String
  endStringRegExNew = startString.replace(new RegExp(/abc/g), "def"); // New Regexp
  endStringStoredRegEx = startString.replace(re, "def") // saved regex
</script>

Chrome 68의 결과는 다음과 같습니다.

String replace:    9,936,093 operations/sec
Saved regex:       5,725,506 operations/sec
Regex:             5,529,504 operations/sec
New Regex String:  3,571,180 operations/sec
New Regex:         3,224,919 operations/sec

이 답변의 완전성을 위해 (주석에서 차용), .replace일치하는 문자의 첫 번째 인스턴스 만 대체 한다는 점 언급 할 가치가 있습니다. 모든 인스턴스를로만 바꿀 수 있습니다 //g. 여러 인스턴스를 교체 name.replace(' ', '_').replace(' ', '_').replace(' ', '_');하거나 더 나쁜 경우 성능 균형 및 코드 우아함이 악화 될 수 있습니다.while (name.includes(' ')) { name = name.replace(' ', '_') }


다음 replace방법 을 사용합니다 .

text = text.replace('old', 'new');

첫 번째 주장은 당신이 찾고있는 것입니다. 정규식도 사용할 수 있습니다.

원래 문자열을 변경 하지는 않습니다 . 새 값만 반환합니다.


더 간단하게 :

city_name=city_name.replace(/ /gi,'_');

모든 공백을 '_'로 바꿉니다!


이 모든 방법은 원래 값을 수정하지 않고 새 문자열을 반환합니다.

var city_name = 'Some text with spaces';

첫 번째 공백 을 _로 바꿉니다.

city_name.replace(' ', '_'); // Returns: Some_text with spaces

정규식을 사용하여 모든 공백 을 _로 바꿉니다 . 정규식을 사용해야하는 경우 https://regex101.com/에서 테스트하는 것이 좋습니다.

city_name.replace(/ /gi,'_');  // Returns: Some_text_with_spaces 

정규식없이 모든 공백 을 _로 바꿉니다 . 기능적인 방법.

city_name.split(' ').join('_');  // Returns: Some_text_with_spaces

다음과 같이 작성해야합니다.

var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);

다른 사람들이 당신에게주는 코드는 한 번만 대체하지만 정규 표현식을 사용하면 모두를 대체합니다 (@sorgit와 같이). 모든 "want"를 "not want"로 바꾸려면 다음 코드를 사용하십시오.

var text = "this is some sample text that i want to replace";
var new_text = text.replace(/want/g, "dont want");
document.write(new_text);

"new_text"변수는 "이것은 바꾸고 싶지 않은 샘플 텍스트입니다"가됩니다.

정규식에 대한 빠른 안내서를 보려면 여기를 방문하십시오.
http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
에 대한 자세한 내용은 https://developer.mozilla.org/를 참조str.replace() 하십시오.
en-US / docs / JavaScript / Reference / Global_Objects / String / replace
행운을 빕니다!


해당 함수는 한 번의 발생 대체합니다 . 여러 발생을 대체해야하는 경우이 기능을 시도해야합니다. http://phpjs.org/functions/str_replace:527

반드시 그런 것은 아닙니다. Hans Kesting의 답변을 참조하십시오.

city_name = city_name.replace(/ /gi,'_');

hm .. replace ()를 확인 했습니까?

코드는 다음과 같습니다

var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);

var new_text = text.replace("want", "dont want");

JavaScript에서는 replaceString 객체 에서 메소드 를 호출합니다 ( 예 : "this is some sample text that i want to replace".replace("want", "dont want")대체 된 문자열을 반환 함).

var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want"); // new_text now stores the replaced string, leaving the original untouched

JavaScript에는 replace()하위 문자열을 대체하기위한 String 객체의 메소드가 있습니다. 이 방법에는 두 가지 인수가있을 수 있습니다. 첫 번째 인수는 문자열 또는 정규식 패턴 (regExp 객체) 일 수 있고 두 번째 인수는 문자열 또는 함수일 수 있습니다. replace()두 문자열 인수를 모두 갖는 메소드 의 예 는 다음과 같습니다.

var text = 'one, two, three, one, five, one';
var new_text = text.replace('one', 'ten');
console.log(new_text)  //ten, two, three, one, five, one

첫 번째 인수가 문자열 인 경우, 위의 예에서와 같이 첫 번째 부분 문자열 만 바뀝니다. 모든 부분 문자열을 바꾸려면 정규 표현식에 g(전역) 플래그 를 제공해야합니다 . 전역 플래그를 제공하지 않으면 정규식을 첫 번째 인수로 제공하더라도 첫 번째 부분 문자열 만 대체됩니다. one위의 예에서 모든 항목을 바꾸겠습니다 .

var text = 'one, two, three, one, five, one';
var new_text = text.replace(/one/g, 'ten');
console.log(new_text)  //ten, two, three, ten, five, ten

정규식 패턴을 따옴표로 묶지 않으면 regExp 객체가 아닌 문자열이됩니다. 대소 문자를 구분하지 않고 교체하려면 i패턴을 대소 문자를 구분하지 않는 추가 플래그를 제공해야합니다 . 이 경우 위의 정규식은입니다 /one/gi. i여기에 추가 플래그를 확인하십시오.

If the second argument has a function and if there is a match the function is passed with three arguments. The arguments the function gets are the match, position of the match and the original text. You need to return what that match should be replaced with. For example,

var text = 'one, two, three, one, five, one';
var new_text = text.replace(/one/g, function(match, pos, text){
return 'ten';
});
console.log(new_text) //ten, two, three, ten, five, ten

You can have more control over the replacement text using a function as the second argument.


There are already multiple answers using str.replace() (which is fair enough for this question) and regex but you can use combination of str.split() and join() together which is faster than str.replace() and regex.

Below is working example:

var text = "this is some sample text that i want to replace";

console.log(text.split("want").join("dont want"));


If you really want a equivalent to PHP's str_replace you can use Locutus. PHP's version of str_replace support more option then what the JavaScript String.prototype.replace supports. For example tags:

//PHP
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
//JS with Locutus
var $bodytag = str_replace(['{body}', 'black', '<body text='{body}'>')  

or array's

//PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
//JS with Locutus
var $vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"];
var $onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

Also this doesn't use regex instead it uses for loops. If you not want to use regex but want simple string replace you can use something like this ( based on Locutus )

function str_replace (search, replace, subject) {

  var i = 0
  var j = 0
  var temp = ''
  var repl = ''
  var sl = 0
  var fl = 0
  var f = [].concat(search)
  var r = [].concat(replace)
  var s = subject
  s = [].concat(s)

  for (i = 0, sl = s.length; i < sl; i++) {
    if (s[i] === '') {
      continue
    }
    for (j = 0, fl = f.length; j < fl; j++) {
      temp = s[i] + ''
      repl = r[0]
      s[i] = (temp).split(f[j]).join(repl)
      if (typeof countObj !== 'undefined') {
        countObj.value += ((temp.split(f[j])).length - 1)
      }
    }
  }
  return s[0]
}
var text = "this is some sample text that i want to replace";

var new_text = str_replace ("want", "dont want", text)
document.write(new_text)

for more info see the source code https://github.com/kvz/locutus/blob/master/src/php/strings/str_replace.js


You can use

text.replace('old', 'new')

And to change multiple values in one string at once, for example to change # to string v and _ to string w:

text.replace(/#|_/g,function(match) {return (match=="#")? v: w;});

You have the following options:

  1. Replace the first occurrence

var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace('want', 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well"
console.log(new_text)

  1. Replace all occurrences - case sensitive

var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace(/want/g, 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well
console.log(new_text)

  1. Replace all occurrences - case insensitive

var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace(/want/gi, 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i dont want to replace as well
console.log(new_text)

More info -> here


In Javascript, replace function available to replace sub-string from given string with new one. Use:

var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
console.log(new_text);

You can even use regular expression with this function. For example, if want to replace all occurrences of , with ..

var text = "123,123,123";
var new_text = text.replace(/,/g, ".");
console.log(new_text);

Here g modifier used to match globally all available matches.


Method to replace substring in a sentence using React:

 const replace_in_javascript = (oldSubStr, newSubStr, sentence) => {
    let newStr = "";
    let i = 0;
    sentence.split(" ").forEach(obj => {
      if (obj.toUpperCase() === oldSubStr.toUpperCase()) {
        newStr = i === 0 ? newSubStr : newStr + " " + newSubStr;
        i = i + 1;
      } else {
        newStr = i === 0 ? obj : newStr + " " + obj;
        i = i + 1;
      }
    });
    return newStr;
  };

RunMethodHere


If you don't want to use regex then you can use this function which will replace all in a string

Source Code:

function ReplaceAll(mystring, search_word, replace_with) 
{
    while (mystring.includes(search_word))
    {
        mystring = mystring.replace(search_word, replace_with);
    }

    return mystring;  
}

How to use:

var mystring = ReplaceAll("Test Test", "Test", "Hello"); 

Use JS String.prototype.replace first argument should be Regex pattern or String and Second argument should be a String or function.

str.replace(regexp|substr, newSubStr|function);

Ex:

var str = 'this is some sample text that i want to replace'; var newstr = str.replace(/want/i, "dont't want"); document.write(newstr); // this is some sample text that i don't want to replace


function str_replace($old, $new, $text)
{
   return ($text+"").split($old).join($new); 
}

You do not need additional libraries.


Added a method replace_in_javascript which will satisfy your requirement. Also found that you are writing a string "new_text" in document.write() which is supposed to refer to a variable new_text.

let replace_in_javascript= (replaceble, replaceTo, text) => {
  return text.replace(replaceble, replaceTo)
}

var text = "this is some sample text that i want to replace";
var new_text = replace_in_javascript("want", "dont want", text);
document.write(new_text);

참고URL : https://stackoverflow.com/questions/5519368/how-can-i-perform-a-str-replace-in-javascript-replacing-text-in-javascript

반응형