const laughing = '小智'.repeat(3)
consol.log(laughing) // "小智小智小智"
const eightBits = '1'.repeat(8)
console.log(eightBits) // "11111111"
有时,我们希望字符串具有特定长度。如果字符串太短,则需要填充剩余空间,直到达到指定的长度为止。
过去,主要还是使用库 left-pad。但是,今天我们可以使用padStart和SpadEnd方法,选择哪种方法取决于是在字符串的开头还是结尾填充字符串。
// 在开头添加 "0",直到字符串的长度为 8。
const eightBits = '001'.padStart(8, '0')
console.log(eightBits) // "00000001"
//在末尾添加“ *”,直到字符串的长度为5。
const anonymizedCode = "34".padEnd(5, "*")
console.log(anonymizedCode) // "34***"
有多种方法可以将字符串分割成字符数组,我更喜欢使用扩展操作符(...):
const word = 'apple'
const characters = [...word]
console.log(characters) // ["a", "p", "p", "l", "e"]
注意,这并不总是像预期的那样工作。有关更多信息,请参见下一个技巧。
const word = "apple";
console.log(word.length) // 5
但对于中文来说,这个方法就不太靠谱。
const word = ""
console.log(word.length) // 2
日本汉字返回length为2,为什么?JS 将大多数字符表示为16位代码点。
但是,某些字符表示为两个(或更多)16 位代码点,称为代理对。如果使用的是length属性,JS 告诉你使用了多少代码点。因此,(hokke)由两个代码点组成,返回错误的值。
那怎么去判断呢,使用解构操作符号(...)
const word = ""
const characters = [...word]
console.log(characters.length) // 1
这种方法在大多数情况下都有效,但是有一些极端情况。例如,如果使用表情符号,则有时此长度也是错误的。如果真想计算字符正确长度,则必须将单词分解为 字素簇(Grapheme Clusters) ,这超出了本文的范围,这里就不在这说明。
反转字符串中的字符是很容易的。只需组合扩展操作符(...)、Array.reverse方法和Array.join方法。
const word = "apple"
const reversedWord = [...word].reverse().join("")
console.log(reversedWord) // "elppa"
和前面一样,也有一些边缘情况。遇到边缘的情况就有需要首先将单词拆分为字素簇。
一个非常常见的操作是将字符串的第一个字母大写。虽然许多编程语言都有一种本地方法来实现这一点,但 JS 需要做一些工作。
let word = 'apply'
word = word[0].toUpperCase() + word.substr(1)
console.log(word) // "Apple"
另一种方法:
// This shows an alternative way
let word = "apple";
// 使用扩展运算符(`...`)拆分为字符
const characters = [...word];
characters[0] = characters[0].toUpperCase();
word = characters.join("");
console.log(word); // "Apple"
假设我们要在分隔符上分割字符串,第一想到的就是使用split方法,这点,智米们肯定知道。但是,有一点大家可能不知道,就是split可以同时拆分多个分隔符, 使用正则表达式就可以实现:
// 用逗号(,)和分号(;)分开。
const list = "apples,bananas;cherries"
const fruits = list.split(/[,;]/)
console.log(fruits); // ["apples", "bananas", "cherries"]
字符串搜索是一项常见的任务。在 JS 中,你可以使用String.includes方法轻松完成此操作。不需要正则表达式。
const text = "Hello, world! My name is Kai!"
console.log(text.includes("Kai")); // true
在字符串的开头或结尾进行搜索,可以使用String.startsWith和String.endsWith方法。
const text = "Hello, world! My name is Kai!"
console.log(text.startsWith("Hello")); // true
console.log(text.endsWith("world")); // false
有多种方法可以替换所有出现的字符串。可以使用String.replace方法和带有全局标志的正则表达式。或者,可以使用新的String.replaceAll方法。请注意,并非在所有浏览器和Node.js 版本中都可用此新方法。
把JavaScript中的string当作字符序列来看待是最直观的,虽然这样并不准确。
以下代码示例中的字符串由5个字母和一个感叹号组成:
const message = 'Hello!';
如果把string当作是可见的字符序列,那么'Hello!'中的字符数是6:
const message = 'Hello!';
message.length; // => 6
如果string中的字符都是ASCII字符,那么通过可见字符的方式对string建模效果很不错。
但是,如果string中出现了更加复杂的字符,比如,,,这时候会出现意想不到的的问题。
const smile = '';
smile.length; // => 2
怎么会这样呢?
这是因为JavaScript将字符串视为码元(code unit)序列,而不是可见字符序列。
让我们更详细地了解JavaScript中的字符串。
The String type is the set of all ordered sequences of zero or more 16-bit unsigned integer values (“elements”). The String type is generally used to represent textual data in a running ECMAScript program, in which case each element in the String is treated as a UTF-16 code unit value.
简而言之,JavaScript中的string是一个数字序列。如果用UTF-16编码的码元来表示'Hello!'这个字符串:
const message = '\u0048\u0065\u006C\u006C\u006F\u0021';
message === 'Hello!'; // => true
message.length; // => 6
因为具有6个码元,这对应于'Hello!'字符串中可见字符的数量。
基本多文种平面(Basic Multilangual Plane)中的字符使用一个UTF-16码元进行编码,但是非基本多文种平面(non-Basic Multilangual Plane)则使用一对不可分割的码元进行编码。
const smile = '\uD83D\uDE00';
smile === ''; // => true
smile.length; // => 2
该序列\uD83D\uDE00是一个特殊的对,称为代理对(surrogate pair)。
字符串迭代器认识代理对。当您调用字符串迭代器时(例如,使用spread运算符)...,它将代理对视为一个长度单位:
onst name="jiajia";
const age=25;
const job="web developer";
const city="beijing";
function hello(){
return "hello jiajia";
}
//es5的 用+号拼接 这里就不展示了,
//以下是 es6写法
html=`
<ul>
<li>name:${name}</li>
<li>age:${age}</li>
<li>job:${job}</li>
<li>city:${city}</li>
<li>${4+4}</li>
<li>${hello()}</li>
</ul>
`;
document.write(html);
*请认真填写需求信息,我们会在24小时内与您取得联系。