Programming

자바 스크립트-문자열에서 모든 쉼표를 교체합니다

procodes 2020. 3. 2. 13:18
반응형

자바 스크립트-문자열에서 모든 쉼표를 교체합니다


이 질문에는 이미 답변이 있습니다.

쉼표가 여러 개인 문자열이 있으며 문자열 바꾸기 메소드는 첫 번째 문자열 만 변경합니다.

var mystring = "this,is,a,test"
mystring.replace(",","newchar", -1)

결과 :"thisnewcharis,a,test"

문서는 기본값이 모두를 대체하고 "-1"도 모두를 대체한다는 것을 나타내지 만 실패합니다. 이견있는 사람?


String.prototype.replace()함수 의 세 번째 매개 변수는 표준으로 정의 된 적이 없으므로 대부분의 브라우저는이를 구현하지 않습니다.

가장 좋은 방법은 ( global ) 플래그 와 함께 정규 표현식 을 사용하는 것입니다 .g

var myStr = 'this,is,a,test';
var newStr = myStr.replace(/,/g, '-');

console.log( newStr );  // "this-is-a-test"

여전히 문제가 있습니까?

정규식 은 이스케이프해야하는 특수 문자를 사용한다는 점에 유의 해야합니다 . 예를 들어, 점 ( .) 문자 를 이스케이프해야하는 경우 /\./정규식 구문에서 점은 단일 문자 (행 종결 자 제외)와 일치하므로 리터럴 을 사용해야합니다 .

var myStr = 'this.is.a.test';
var newStr = myStr.replace(/\./g, '-');

console.log( newStr );  // "this-is-a-test"

정규식 리터럴을 사용하는 대신 변수를 대체 문자열로 전달해야하는 경우 RegExp객체를 생성 하고 생성자의 첫 번째 인수로 문자열을 전달할 수 있습니다 . 일반적인 문자열 이스케이프 규칙 (문자열에 \포함 된 선행 특수 문자 )이 필요합니다.

var myStr = 'this.is.a.test';
var reStr = '\\.';
var newStr = myStr.replace(new RegExp(reStr, 'g'), '-');

console.log( newStr );  // "this-is-a-test"


재미로:

var mystring = "this,is,a,test"  
var newchar = '|'
mystring = mystring.split(',').join(newchar);

var mystring = "this,is,a,test"
mystring.replace(/,/g, "newchar");

global ( g) 플래그를 사용하십시오.

간단한 데모

참고 URL : https://stackoverflow.com/questions/10610402/javascript-replace-all-commas-in-a-string



반응형