반응형
자바스크립트 .replace는 첫번째 Match만 바꿉니다.
var textTitle = "this is a test"
var result = textTitle.replace(' ', '%20');
하지만 교체 기능은 ""의 첫 번째 인스턴스에서 중지되고 저는 다음을 이해합니다.
결과:"this%20is a test"
내가 어디서 잘못되고 있는지에 대한 어떤 아이디어라도 있다면 나는 그것이 간단한 해결책이라고 확신합니다.
당신은 필요합니다./g
그 위에, 다음과 같이.
var textTitle = "this is a test";
var result = textTitle.replace(/ /g, '%20');
console.log(result);
여기서 기본적으로 사용할 수 있습니다..replace()
동작은 첫 번째 일치만 대체하는 것이고, 수정자(global)는 모든 발생을 대체하는 것을 말합니다.
textTitle.replace(/ /g, '%20');
마찬가지로 문자열에서 "generic" regex가 필요한 경우:
const textTitle = "this is a test";
const regEx = new RegExp(' ', "g");
const result = textTitle.replace(regEx , '%20');
console.log(result); // "this%20is%20a%20test" will be a result
replace() 메서드는 부분 문자열(또는 정규식)과 문자열 간의 일치를 검색하고 일치하는 부분 문자열을 새 부분 문자열로 바꿉니다.
그렇다면 여기서 regex를 사용하는 것이 좋습니다.
textTitle.replace(/ /g, '%20');
첫 번째 인수에 문자열 대신 regex를 사용해 보십시오.
"this is a test".replace(/ /g,'%20')
// #=> "이 %20은 %20a%20 테스트"
이를 위해서는 regex의 g 플래그를 사용해야 합니다.이와 같이:
var new_string=old_string.replace( / (regex) /g, replacement_text);
that
사용해보기replaceWith()
아니면replaceAll()
http://api.jquery.com/replaceAll/
언급URL : https://stackoverflow.com/questions/3214886/javascript-replace-only-replaces-first-match
반응형
'programing' 카테고리의 다른 글
'table'에서 'alias'로 삭제...여기서 'alias'.'열'...왜 구문 오류입니까? (0) | 2023.11.04 |
---|---|
WooCommerce에서 모든 체크아웃 필드를 가져오는 방법은? (0) | 2023.11.04 |
800px 이후 divon 스크롤다운 표시 (0) | 2023.11.04 |
Tensorflow에서 그래프의 모든 Tensor의 이름을 가져옵니다. (0) | 2023.10.30 |
면도기 뷰에서 .css 파일을 참조하는 방법은 무엇입니까? (0) | 2023.10.30 |