본문 바로가기

JavaScript

JS 문자열 메서드 훑고 가기.

// 문자열 객체 선언
var str1 = new String("str1");
var str2 = "str2";

// charAt();
var str = "Hello";
var result = str.charAt(1); // 'e'

//.indexOf("찾을 문자", index)  두번째 인자는 시작 index를 지정한다.
var str = "Hello World!";
var result_indexOf = str.indexOf("World"); // 6

// replace("찾을 문자", "치환할 문자");
var str = "Hello World!";
var result = str.replace("Hello", "Hi"); // "Hi World!"
// 가장 왼쪽에 나오는 것을 변경해준다.

//subString(), substr()
//string.substring(startIndex, endIndex)
//string.subStr(startIndex, 문자개수)
var str = "Hello World"
var result_substring = str.substring(0, 5);  // "Hello"
var result_substr = str.substr(6,5);  // "World" 

// slice()
var str1 = 'The morning is upon us.',
	str2 = str1.slice(1, 8),	// he morn
	str3 = str1.slice(4,-2),	// morining us upon u
	str4 = str1.slice(12),		// is upon us.
	str5 = str1.slice(30);		// ""

// split()  : str.split([separator[, limit]])
const str = 'The quick brown fox jumps over the lazy dog.';

const words = str.split(' ');
console.log(words[3]); // "fox"

const chars = str.split('');
console.log(chars[8]); // "k"


// concat() : str.concat(string2, string3[, ..., stringN])
const str1 = "Hello";
const str2 = "World";

console.log(str.consat(' ', str2)); // "Hello World"

console.log(str2.concat(', ', str1)); // "World, Hello"

// trim() 문자열 양쪽 끝에 공백을 제거해주는 함수.

'JavaScript' 카테고리의 다른 글

node / express 공부기.  (0) 2020.04.25
JS 배열 정리하고 가기.  (0) 2020.04.24
You Don't Know Node / translate  (0) 2020.04.22
var / let / const 간단정리  (0) 2020.04.22
closure  (0) 2020.04.22