字符串方法

86 阅读1分钟

if 测试中 indexOf 有一点不方便。我们不能像这样把它放在 if 中:

let str = "Widget with id";

if (str.indexOf("Widget")) {
    alert("We found it"); // 不工作!
}

上述示例中的 alert 不会显示,因为 str.indexOf("Widget") 返回 0(意思是它在起始位置就查找到了匹配项)。是的,但是 if 认为 0 表示 false

因此我们应该检查 -1,像这样:

let str = "Widget with id";

if (str.indexOf("Widget") != -1) {
    alert("We found it"); // 现在工作了!
}

对于 32-bit 整数,~n 等于 -(n+1)

只有当 n == -1 时,~n 才为零(适用于任何 32-bit 带符号的整数 n)。

方法选择方式……负值参数
slice(start, end)startend(不含 end允许
substring(start, end)startend 之间(包括 start,但不包括 end负值代表 0
substr(start, length)start 开始获取长为 length 的字符串允许 start 为负数
str.codePointAt(pos)

返回在 pos 位置的字符代码 :

// 不同的字母有不同的代码
alert( "z".codePointAt(0) ); // 122
alert( "Z".codePointAt(0) ); // 90
String.fromCodePoint(code)

通过数字 code 创建字符

alert( String.fromCodePoint(90) ); // Z

我们还可以用 \u 后跟十六进制代码,通过这些代码添加 unicode 字符:

// 在十六进制系统中 90 为 5a
alert( '\u005a' ); // Z