IT/Javascript

JavaScript 문자열대체 / 공백제거 / replace / replace All

K_sun 2021. 4. 18. 20:24

JavaScript 문자열대체 / 공백제거 / replace / replace All

 

 

 

1. 문자열 양쪽 끝 공백제거(trim)

var str = " a b c "
str = str.trim();
// "a b c"

 

 

 

2. 문자열 대체(replace)

const newStr = str.replace(regexp|substr, newSubstr|function)
var fruit = "apple tomato banana";
fruit = fruit.replace("apple","orange");
// "orange tomato banana"

 

 

 

2-1. 문자열 제거

 - 찾는 패턴에 해당하는 항목이 여럿이더라도, 문자열 인덱스상에서 맨앞의 항목만 변경됩니다.

var fruit = "apple tomato banana";
fruit = fruit.replace("a","");
// "pple tomato banana"

 

 

 

 

2-2. 패턴 전체항목에 적용

 - 패턴 전체에 적용하게 하기위해, 정규표현식을 이용해야 합니다.

 - g : 모든패턴 항목에 대한 검색 

 - i : 대소문자 구분하지않고 검색 

var fruit = "apple tomato banana";
fruit = fruit.replace(/a/gi,"");
// "pple tomto bnn"

 

 

 - 문자열 전체 공백제거

var fruit = "apple tomato banana";
fruit = fruit.replace(/ /gi,"");
// "appletomatobanana"

 

 

 - 날짜(yyyy-mm-dd ) 타입 문자열에서 "-" 제거하기 

var fruit = "2021-04-18";
str.replace(/-/gi,"");
// "20210418"

 

 

 

※ replaceAll

 - javascript에서도 replaceAll이 있긴하지만, replace함수와 다르게 브라우저 제약성이 존재합니다.

출처. developer.mozilla.org (클릭시 해당Document로 이동)