11 个你应该知道的JavaScript 字符串的基础知识
英文 | https://medium.com/dailyjs/javascript-strings-10-fundamentals-you-should-know-d29e6e5f3a1a
"text"
'text'
"text" === 'text'
//true
"text with \"double quotes\" inside"
'text with "double quotes" inside'
"text with single 'quotes' "
"Text" === "Text"
//true
"The first line\nThe second line"
const str = "abc";
const newStr = str.replace("a", "A");
console.log(str);
//"abc"
console.log(newStr)
//"Abc"
const text = 'ABC';
text[0] = 'X';
//TypeError: Cannot assign to read only property '0' of string 'ABC'
new String(" text ").trim();
const text = " \t\ntext\n\t ";
const newText = text.trim();
//"text"
String(0)
//'0'
String(true)
//'true'
String(null)
//'null'
String(undefined)
//'undefined'
String([1,2,3])
//'1,2,3'
String({ msg: 'Hi'})
//'[object Object]'
String(Symbol('id'))
//'Symbol(id)'
"A" + " " + "text"
//"A text"
1 + "2"
//"12"
"A".concat("B")
//"AB"
"A".concat(" ", "text")
//"A text"
"1".concat(2)
//"12"
const quote = 'Winter is coming';
const words = quote.split(' ');
//["Winter", "is", "coming"]
const csv = 'Fire,and,Blood';
const arr = csv.split(',');
//["Fire", "and", "Blood"]
const arr = ['Fire', 'and', 'Blood'];
const text = arr.join(' ');
//'Fire and Blood'
const quote = "Here we stand";
const firstIndex = quote.indexOf(" ");
console.log(firstIndex) //4
const quote = "Here we stand";
const lastIndex = quote.lastIndexOf(" ");
console.log(lastIndex) //7
const quote = "First in Battle";
console.log(quote.startsWith("First"));
//true
const quote = "We Remember";
console.log(quote.endsWith("We"));
//false
const quote = "Our Blades are Sharp";
console.log(quote.includes("are"));
//true
const quote = "Winter is coming";
const part1 = quote.substr(0, 6);
//Winter
const part2 = quote.substr(10, 6);
//coming
const quote = "Winter is coming";
const part = quote.substr(6);
// is coming
const quote = "We Stand Together";
const part = quote.substring(3, 8);
// Stand
const quote = "We Stand Together";
const part = quote.substring(3);
// Stand Together
const quote = "You know nothing,Jon Snow";
const commaIndex = quote.indexOf(",");
const part = quote.substring(commaIndex + 1);
//"Jon Snow"
`Wisdom
and
Strength`
const word = "Awake";
`${word}! ${word}!`
//"Awake! Awake!"
const word = 'Hi';
console.log(word.length)
//2
const word = 'Hi🙂';
console.log(word.length)
//4
const word = 'Hi;
console.log(word.charAt(0))
//H
const word = 'Hi🙂';
console.log(word.charAt(2))
//�
const word = 'Hi🙂';
const chars = word.split("");
//["H", "i", "�", "�"]
const word = 'Hi🙂';
const chars = Array.from(word);
console.log(word.length);
//4
console.log(chars.length);
//3
console.log(chars[2]);
//🙂
学习更多技能
请点击下方公众号
评论