๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“’ JavaScript

JavaScript replace์— ๋ณ€์ˆ˜ ํ™œ์šฉํ•˜๊ธฐ - ์ •๊ทœํ‘œํ˜„์‹ (regExp) ์ด์šฉ

by Tamii 2022. 5. 17.
๋ฐ˜์‘ํ˜•

์„œ๋น„์Šค๋ฅผ ๋งŒ๋“ค ๋•Œ, JavaScript replace์— ๋ณ€์ˆ˜๋ฅผ ๋„ฃ์–ด์•ผ ํ•œ๋Š” ์ƒํ™ฉ์ด ์ข…์ข… ์ƒ๊น๋‹ˆ๋‹ค.

 

 

 

์˜ˆ๋ฅผ ๋“ค์–ด

์–ด๋–ค URL์˜ ๊ฒฝ๋กœ๋งŒ ๊ตฌํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•œ๋‹ค๊ณ  ํ•ด๋ด…์‹œ๋‹ค.

const red = 'apple'
const sentence = 'I want red apple cookies';

const ans = sentence.replace(/red/gi,'');

 

๋‚ด๊ฐ€ ์›ํ•œ ๊ฒƒ :  I want red cookies

์‹ค์ œ ์‹คํ–‰๋˜๋Š”๊ฒƒ : I want apple cookies

 

replace์•ž์— ๋“ค์–ด๊ฐ€๋Š” ๊ฒƒ์€ ์ •๊ทœํ‘œํ˜„์‹ ํ˜น์€ string๊ทธ ์ž์ฒด์ด๊ธฐ ๋•Œ๋ฌธ์— ๋‹น์—ฐํžˆ red๊ฐ€ ์น˜ํ™˜๋˜๊ฒŒ ๋œ๋‹ค.

 

 

 

new ReqExp ํ™œ์šฉํ•˜๊ธฐ

๐Ÿ”— MDN - RegExp

const red = 'apple'
const sentence = 'I want red apple cookies';


// ๋Œ€์†Œ๋ฌธ๊ฐ€ ๊ตฌ๋ถ„ ์—†์ด ์ผ์น˜ํ•˜๋Š” ๊ฒƒ์„ ์ฐพ์•„ ์ ์šฉ
const redRegExp = new ReqExp(red,'gi')

const ans = sentence.replace(redRegExp,'');

// I want red cookies

 

 

๐Ÿฅณ ์™„์„ฑ!

๋Œ“๊ธ€