Programming/JavaScript

[JavaScript] ํŠน์ • ๋ฌธ์ž ์ „๊นŒ์ง€ ๋ฌธ์ž์—ด ์ž๋ฅด๋Š” ๋ฐฉ๋ฒ• (substring ์ด์šฉ)

yuri lee 2022. 10. 1. 11:10
๋ฐ˜์‘ํ˜•

Intro

ํŠน์ • ๋ฌธ์ž ์ „๊นŒ์ง€ ๋ฌธ์ž์—ด์„ ์ž๋ฅด๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค. 

 

"message" : "No: 1, 2\nHello World!"

 

๊ตฌ์ฒด์ ์ธ ์˜ˆ์‹œ๋ฅผ ๋“ค์–ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. ๋‹ค์Œ์˜ ๋ฐ์ดํ„ฐ๊ฐ€ ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด๋ด…์‹œ๋‹ค. ๊ธฐ์กด์—๋Š” message์— ํ•ด๋‹นํ•˜๋Š” value (string) ๊ฐ’์„ ํ™”๋ฉด์— ๊ทธ๋Œ€๋กœ ํ‘œ์ถœํ•˜์˜€์Šต๋‹ˆ๋‹ค.ํ•˜์ง€๋งŒ ์œ„ ๋ฌธ์ž์—ด์—์„œ \n ์„ ๊ธฐ์ค€์œผ๋กœ ํ•˜์—ฌ ๋‹จ์ˆœํ•˜๊ฒŒ No: 1, 2 ๋งŒ ํ‘œ์‹œ๋ฅผ ํ•ด์•ผ ํ•œ๋‹ค๋ฉด ์–ด๋–ค ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•ด์•ผ ํ• ๊นŒ์š”?

 

How to solve the problem

javascript์˜ ๋‚ด์žฅ ํ•จ์ˆ˜์ธ substring() ์™€ indexOf()๋ฅผ ํ™œ์šฉํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค. indexOf()๋กœ index 8์„ ๋ฐ˜ํ™˜ํ•˜๋ฏ€๋กœ ์ตœ์ข…์ ์œผ๋กœ substring(0, 8) ์ด ๋ฉ๋‹ˆ๋‹ค. ํ•ด๋‹น ๋ฌธ์ž์—ด์—์„œ ์ธ๋ฑ์Šค 0๋ถ€ํ„ฐ 8์ „๊นŒ์ง€์˜ ๋ฌธ์ž์—ด์„ ์ตœ์ข… ๋ฐ˜ํ™˜ํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. 

const message = "No: 1, 2\nHello World!"

function getMessage(string) {
    return string.substring(0, string.indexOf('\n'));
}

getMessage(message)
// expected output: "No: 1, 2"
  • substring() : string ๊ฐ์ฒด์˜ ์‹œ์ž‘ index ๋ถ€ํ„ฐ ์ข…๋ฃŒ index ์ „๊นŒ์ง€ ๋ฌธ์ž์—ด์˜ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. 
  • indexOf() : ํ˜ธ์ถœํ•œ string ๊ฐ์ฒด์—์„œ ์ฃผ์–ด์ง„ ๊ฐ’๊ณผ ์ผ์น˜ํ•˜๋Š” ์ฒซ ๋ฒˆ์งธ index๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. 

 


https://stackoverflow.com/questions/9133102/how-to-grab-substring-before-a-specified-character-in-javascript

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/substring

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

๋ฐ˜์‘ํ˜•