MDN String的属性和方法


// concat 连接字符串
let hello = 'hello';
hello.concat(',', 'world');   // hello,world

// endsWith 判断是不是以...结尾
hello.endsWith('o')   // true

// includes 是否包含
hello.includes('l')    // true

// match 匹配字符串中符合的字符,返回数组
let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
let regexp = /[A-E]/gi;
let matches_array = str.match(regexp);

console.log(matches_array);// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']

// padEnd 填充结尾
'abc'.padEnd(10, '');          // "abc       "

// padStart 填充开始
'abc'.padStart(10, '');          // "       abc"

// repeat 重复
"abc".repeat(2)      	// "abcabc"

// replace 替换
var str = 'Twas the night before Xmas...';
var newstr = str.replace(/xmas/i, 'Christmas');
console.log(newstr);  // Twas the night before Christmas...

// slice 根据索引截取字符串,slice() 提取的新字符串包括beginSlice但不包括 endSlice。
var str1 = 'The morning is upon us.';
var str2 = str1.slice(4, -2);

// substr 根据开始索引和长度截取字符串
'abcde'.substr(1, 2)	// 'bc'

// substring 根据索引截取字符串,substring() 提取的新字符串包括beginSlice但不包括 endSlice。
'Mozilla'.substring(0,3)	// 'Moz'

console.log(str2); // OUTPUT: morning is upon u

// split 分隔字符串
"Webkit Moz O ms Khtml".split( " " )   // ["Webkit", "Moz", "O", "ms", "Khtml"]

// 以...开始 startsWith
'To be a teacher'.startsWith("To be")	// true

// trim 去除空格
'   abc    '.trim()		// 'abc'

// trimLeft trimRight	去除左边空格 去除右边空格


猜你喜欢

转载自my.oschina.net/chinahufei/blog/1826211
今日推荐