javascript中的字符串
Posted 低代码布道师
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript中的字符串相关的知识,希望对你有一定的参考价值。
可以使用单引号、双引号、反引号来定义字符串
let single = 'single-quoted';
let double = "double-quoted";
let backticks = `backticks`;
反引号里可以嵌套表达式,表达式要以${}
包裹
function sum(a, b) {
return a + b;
}
alert(`1 + 2 = ${sum(1, 2)}.`); // 1 + 2 = 3.
此外,反引号允许字符串以多行出现
let guestList = `Guests:
* John
* Pete
* Mary
`;
alert(guestList); // a list of guests, multiple lines
可以使用换行符\\n
let str1 = "Hello\\nWorld"; // two lines using a "newline symbol"
// two lines using a normal newline and backticks
let str2 = `Hello
World`;
alert(str1 == str2); // true
可以计算字符串长度,通过调用length属性即可
alert( `My\\n`.length ); // 3
可以使用中括号的语法来访问某一个字符,或者使用charAt方法
let str = `Hello`;
// the first character
alert( str[0] ); // H
alert( str.charAt(0) ); // H
// the last character
alert( str[str.length - 1] ); // o
也可以使用for of语句来迭代字符串
for (let char of "Hello") {
alert(char); // H,e,l,l,o (char becomes "H", then "e", then "l" etc)
}
字符串被定义后,不能单独改变某个字符
let str = 'Hi';
str[0] = 'h'; // error
alert( str[0] ); // doesn't work
但是可以将值赋予一个新的字符串
let str = 'Hi';
str = 'h' + str[1]; // replace the string
alert( str ); // hi
可以使用indexOf来查找字符串第一次出现的位置,如果没有找到就返回-1
let str = 'Widget with id';
alert( str.indexOf('Widget') ); // 0, because 'Widget' is found at the beginning
alert( str.indexOf('widget') ); // -1, not found, the search is case-sensitive
alert( str.indexOf("id") ); // 1, "id" is found at the position 1 (..idget with id)
也可以从某个位置找起,indexOf接收第二个参数,表示从哪找起
let str = 'Widget with id';
alert( str.indexOf('id', 2) ) // 12
可以使用includes来判断字符串是否存在
alert( "Widget with id".includes("Widget") ); // true
alert( "Hello".includes("Bye") ); // false
可以使用startWith或者endWith来查询字符串的开头和结尾
alert( "Widget".startsWith("Wid") ); // true, "Widget" starts with "Wid"
alert( "Widget".endsWith("get") ); // true, "Widget" ends with "get"
可以使用slice截取子串
let str = "stringify";
alert( str.slice(0, 5) ); // 'strin', the substring from 0 to 5 (not including 5)
alert( str.slice(0, 1) ); // 's', from 0 to 1, but not including 1, so only character at 0
substring和slice差不多,不过起始位置可以比结束位置大
let str = "stringify";
// these are same for substring
alert( str.substring(2, 6) ); // "ring"
alert( str.substring(6, 2) ); // "ring"
substr从开始位置截取length个长度字符串
let str = "stringify";
alert( str.substr(2, 4) ); // 'ring', from the 2nd position get 4 characters
以上是关于javascript中的字符串的主要内容,如果未能解决你的问题,请参考以下文章
精心收集的 48 个 JavaScript 代码片段,仅需 30 秒就可理解!(转载)