티스토리 뷰
5.3 Strings
Quetes
javascript에서 싱글, 더블, 백틱 상관없이 뭐든지 문자열을 표현하는데, 사용가능하다. 다만 백틱을 사용할 경우 줄바꿈이나 표현식을 삽입하는 것이 가능하다.
function sum(a, b) {
return a + b;
}
alert(`1 + 2 = ${sum(1, 2)}.`); // 1 + 2 = 3.
// -------------------
let guestList = `Guests:
* John
* Pete
* Mary
`;
alert(guestList); // a list of guests, multiple lines
String length
alert( `My\n`.length ); // 3
Accessing characters
let str = `Hello`;
// the first character
alert( str[0] ); // H
alert( str.at(0) ); // H
// the last character
alert( str[str.length - 1] ); // o
alert( str.at(-1) );
// ------------------------
let str = `Hello`;
alert( str[-2] ); // undefined
alert( str.at(-2) ); // l
Strings are immutable
문자열은 기본적으로 변경이 불가해서, 기존 변수에 새로운 문자열을 생성하고 할당하는 방식으로 사용한다.
let str = 'Hi';
str[0] = 'h'; // error
alert( str[0] ); // doesn't work
// -------------------
let str = 'Hi';
str = 'h' + str[1]; // replace the string
alert( str ); // hi
Searching for a substring
let str = 'Widget with id';
alert( str.indexOf('Widget') ); // 0, because 'Widget' is found at the beginning
alert( str.indexOf('widget') ); // -1, not found, the search is case-sensitive
alert( str.indexOf("id") ); // 1, "id" is found at the position 1 (..idget with id)
// ----------------------
let str = 'Widget with id';
alert( str.indexOf('id', 2) ) // 12
alert( "Widget with id".includes("Widget") ); // true
alert( "Hello".includes("Bye") ); // false
alert( "Widget".includes("id") ); // true
alert( "Widget".includes("id", 3) ); // false, from position 3 there is no "id"
alert( "Widget".startsWith("Wid") ); // true, "Widget" starts with "Wid"
alert( "Widget".endsWith("get") ); // true, "Widget" ends with "get"
Getting a substring
let str = "stringify";
alert( str.slice(0, 5) ); // 'strin', the substring from 0 to 5 (not including 5)
alert( str.slice(0, 1) ); // 's', from 0 to 1, but not including 1, so only character at 0
let str = "stringify";
alert( str.slice(2) ); // 'ringify', from the 2nd position till the end
let str = "stringify";
// start at the 4th position from the right, end at the 1st from the right
alert( str.slice(-4, -1) ); // 'gif'
Comparing strings
// different case letters have different codes
alert( "Z".codePointAt(0) ); // 90
alert( "z".codePointAt(0) ); // 122
alert( "z".codePointAt(0).toString(16) ); // 7a (if we need a hexadecimal value)
alert( String.fromCodePoint(90) ); // Z
alert( String.fromCodePoint(0x5a) ); // Z (we can also use a hex value as an argument)
'스터디 > JavaScript' 카테고리의 다른 글
모던 자바스크립트 튜토리얼 part1 - 5.5 (0) | 2024.05.20 |
---|---|
모던 자바스크립트 튜토리얼 part1 - 5.4 (0) | 2024.05.20 |
모던 자바스크립트 튜토리얼 part1 - 5.1 ~ 2 (0) | 2024.05.17 |
모던 자바스크립트 튜토리얼 part1 - 4.8 (0) | 2024.05.17 |
모던 자바스크립트 튜토리얼 part1 - 4.6 ~ 7 (0) | 2024.05.17 |
댓글