JavaScript Zero to Hero Chapter 1 – 문자열과 정규 표현식 p.16-28
Keywords in Chapter 1
Regular Expressions
Strings
Methods used to process the strings
Keywords of today's reading
Unicode
Characters and Code Points
Strings
Methods
Unicode
unicorde is a universal character set
컴퓨터는 인간이 쓰는 언어의 철자를 이해 못 하는 대신 글자를 연속된 배열(the sequence of characters)로 이해한다. 그래서 우리는 Unicode를 필요로 한다. Unicode는 글자 목록을 제공하고 각 글자마다 고유한 code point를 부여한다. code point란 Unicode가 한 글자마다 부여하는 숫자를 뜻하는데 U+000부터 U+10FFF까지 있다. U+뒤에는 16진법으로 나타낸 숫자가 온다.
JavaScript는 Unicode character set을 인코딩한 UTF-16을 사용한다. ECMAScript에서는 Strings를 다음과 같이 정의한다.
“ The String type is the set of all ordered sequences of zero or more 16-bit
unsigned integer values (“elements”). The String type is generally used to
represent textual data in a running ECMAScript program, in which case
each element in the String is treated as a UTF-16 code unit value. “
무슨 말인지 모르겠다면 아래 예제를 보며 이해를 해보자!
위 예제에서 보듯 message란 변수는 글자를 5개 가진다. 즉 Strings는 철자, 숫자, 구두점과 같은 연속된 글자의 모음이다. 허나 아래 예제를 보면 헷갈릴 수 있다.
왜 이모티콘은 하나인데 글자 길이는 2라고 나오는가? 바로 JavaScript는 이모티콘을 두 개의 독립된 코드가 연속된 것이라 인식하기 때문이다.
JavaScript의 String은 UTF-16 codepoints의 연속된 배열이다.
message라는 변수값 "Hello"라는 글자 하나하나마다 유니코드가 부여된 것을 볼 수 있다. 즉 JavsScript에서 String을 배열처럼 활용 가능하다는 것이다. String의 Index값은 배열과 마찬가지로 0부터 시작한다.
이제 각 글자에는 고유한 code point가 부여된다는 것을 알았으니 이를 활용할 method 2가지를 살펴보자
- String.fromCodePoint(num1,...,numN): code point를 parameter로 입력하여 입력한 code point에 해당하는 문자를 반환하는 method MDN_Link
console.log(String.fromCodePoint(9731, 9733, 9842, 0x2F804));//☃★♲你
- codePointAt(): 각 문자의 code point를 알아내는 method MDN_Link
const message ='Hello World!';
const codePointsArray = [];
//we can traverse through our newly created string with a for loop
for (let i = 0; i < message.length; i++) {
let codePoint = message.codePointAt(i);
//console.log(codePoint);
codePointsArray[i] = codePoint;}
//this should return back 'Hello World!'
console.log(String.fromCodePoint(...codePointsArray));
String methods you should know about
- repeat(): 해당 string 반복 입력 MDN_Link
//1) repeat method
const message = 'W';
const repeatIt = message.repeat(3);
console.log(repeatIt);// 'WWW'
- trim(): 앞뒤 공백 제거 MDN_Link
- trimStart(): string 앞 공백 제거 MDN_Link
- trimEnd(): string 뒤 공백 제거 MDN_Link
- padStart(): 공백 혹은 주어진 padding style을 string.length가 targetlength에 이를 때까지 앞에서부터 채워넣기 MDN_Link
padStart(targetLength)
padStart(targetLength, padString)
const newString1 = example.padStart(10, '#');
console.log(newString1); // #####Hello
- padEnd(): 공백 혹은 주어진 padding style을 string.length가 targetlength에 이를 때까지 뒤에서부터 채워넣기 MDN_Link
- toUpperCase(): string 대문자로 변환 MDN_Link
- toLowerCase(): string 소문자로 변환 MDN_Link
const firstName = 'Andy';
const lastName = 'Garcia';
console.log(firstName.toLocaleLowerCase());//adny
console.log(lastName.toUpperCase());//GARCIA
- charAt(): 입력한 index값 위치에 있는 string을 반환 MDN_Link
const sentence = 'I want to be a developer!';
const index = 7;
console.log(`The character at index ${index} is ${sentence.charAt(index)}`);// t
- includes(): string이 substring을 포함하는지에 따라 결과값을 boolean형식으로 출력 MDN_Link
const occupation = 'Web Developer';
if (occupation.includes('Dev')) {
console.log(`Yes, it does!`);
} else {
console.log(`Nope I can't find Dev here!`);
}
- slice(): 입력된 시작점을 포함하여 끝점 사이에 있는 string을 반환 MDN_Link
const MyOccupation = 'Developer';
console.log(MyOccupation.slice(0, 3)); // "Dev"
console.log(MyOccupation.slice(2));// "veloper"
- replace(): string 내 substring을 찾아 new string으로 변경 MDN_Link
const originalString = 'mozilla';
const updatedString = originalString.replace('mo','God');
console.log(updatedString); // "Godzilla"
console.log(originalString); // "Mozilla"
const message1 = 'Ana';
const message2 ='maria';
const newMessage = message1.concat(message2);
console.log(newMessage);//Anamaria
- match(): 주어진 regular expression에 해당 string이 있는지 찾고 있다면 해당 string을, 없다면 null을 반환 MDN_Link
let text1 = "Regular expression";
const result = text1.match(/xpr/g);
console.log(result); // "xpr"
댓글