[Javascript] String

Suyeon·2020년 8월 27일
0

Javascript

목록 보기
8/31

Line Break (Multiple lines)

  • Backtics
  • \n with quotes (newline character)
// Backtics
let str1 = `Hello
World`;

// /n
let str2 = "Hello\nWorld";

Special Character

Accessing characters

let str = `Hello`;

// the first character
alert( str[0] ); // H
alert( str.charAt(0) ); // H

// the last character
alert( str[str.length - 1] ); // o

// Difference
alert( str[1000] ); // undefined
alert( str.charAt(1000) ); // '' 

// For...of 
for (let char of "Hello") {
  alert(char); // H,e,l,l,o 
}

Searching for a substring

// str.indexOf(substr, pos)
let str = 'Widget with id';

alert( str.indexOf('Widget') ); // 0
alert( str.indexOf('widget') ); // -1
alert( str.indexOf("id") ); // 1
alert( str.indexOf('id', 2) ) // 12

// Finding all indexes of specified string
var str = "scissors";
var indices = [];

for(var i=0; i<str.length;i++) {
    if (str[i] === "s") indices.push(i);
}

Be careful when use "if" statement

let str = "Widget with id";

// Doesn't work
if (str.indexOf("Widget")) { // Returns 0(false)
    alert("We found it"); 
}

// works now!
if (str.indexOf("Widget") != -1) {
    alert("We found it"); 
}

Getting a substring

// (1) str.slice(start [, end])
let str = "stringify";

alert( str.slice(0, 5) ); // 'strin'
alert( str.slice(0, 1) ); // 's'
alert( str.slice(2) ); // 'ringify'

// (2) str.substring(start [, end])
alert( str.substring(2, 6) ); // "ring"
alert( str.substring(6, 2) ); // "ring", It allows start to be greater than end.

// (3) str.substr(start [, length])
alert( str.substr(2, 4) ); // "ring"
alert( str.substr(-4, 2) ); // "gi"

The others methods

// toUpperCase /  toLowerCase

// includes / strtsWith / endsWith : returns boolean
alert( "Widget with id".includes("Widget") ); // true
alert( "Widget".startsWith("Wid") ); 
alert( "Widget".endsWith("get") );

//  localeCompare: compare strings in different languages, following their rules.
alert( 'Österreich'.localeCompare('Zealand') ); // -1, (str is less than str2)
profile
Hello World.

0개의 댓글