文章目录
一、描述
字符串对于保存可以以文本形式表示的数据非常有用。 一些常用的字符串操作有:查询字符串长度,使用 + 和 += 运算符来构建和连接字符串,使用 indexOf 方法检查某一子字符串在父字符串中的位置,又或是使用 substring 方法提取从父字符串中提取子字符串。
基本字符串和字符串对象的区别
字符串字面量 (通过单引号或双引号定义) 和 直接调用 String 方法(没有通过 new 生成字符串对象实例)的字符串都是基本字符串。JavaScript会自动将基本字符串转换为字符串对象,只有将基本字符串转化为字符串对象之后才可以使用字符串对象的方法。当基本字符串需要调用一个字符串对象才有的方法或者查询值的时候(基本字符串是没有这些方法的),JavaScript 会自动将基本字符串转化为字符串对象并且调用相应的方法或者执行查询。
var s_prim = "foo";
var s_obj = new String(s_prim);
console.log(typeof s_prim); // Logs "string"
console.log(typeof s_obj); // Logs "object"
长字符串
有时,你的代码可能含有很长的字符串。你可能想将这样的字符串写成多行,而不是让这一行无限延长或着被编辑器折叠。有两种方法可以做到这一点。
其一,可以使用 + 运算符将多个字符串连接起来,如下所示:
let longString = "This is a very long string which needs " +
"to wrap across multiple lines because " +
"otherwise my code is unreadable.";
其二,可以在每行末尾使用反斜杠字符(“\”),以指示字符串将在下一行继续。确保反斜杠后面没有空格或任何除换行符之外的字符或缩进; 否则反斜杠将不会工作。 如下所示:
let longString = "This is a very long string which needs \
to wrap across multiple lines because \
otherwise my code is unreadable.";
二、方法
1.charAt()
字符串中的字符从左向右索引,第一个字符的索引值为 0,最后一个字符(假设该字符位于字符串 stringName 中)的索引值为 stringName.length - 1。 如果指定的 index 值超出了该范围,则返回一个空字符串。
var anyString = "Brave new world";
console.log("The character at index 0 is '" + anyString.charAt(0) + "'");
console.log("The character at index 1 is '" + anyString.charAt(1) + "'");
console.log("The character at index 2 is '" + anyString.charAt(2) + "'");
console.log("The character at index 3 is '" + anyString.charAt(3) + "'");
console.log("The character at index 4 is '" + anyString.charAt(4) + "'");
console.log("The character at index 999 is '" + anyString.charAt(999) + "'");
2.endsWith()
方法用来判断当前字符串是否是以另外一个给定的子字符串“结尾”的,根据判断结果返回 true 或 false。这个方法是大小写敏感的。
var str = "To be, or not to be, that is the question.";
alert( str.endsWith("question.") ); // true
alert( str.endsWith("to be") ); // false
alert( str.endsWith("to be", 19) ); // true
3、includes()
这个方法可以帮你判断一个字符串是否包含另外一个字符串。includes() 方法是区分大小写的
var str = 'To be, or not to be, that is the question.';
console.log(str.includes('To be')); // true
console.log(str.includes('question')); // true
console.log(str.includes('nonexistent')); // false
console.log(str.includes('To be', 1)); // false
console.log(str.includes('TO BE')); // false
4、indexOf()
方法返回调用它的 String 对象中第一次出现的指定值的索引,从 fromIndex 处进行搜索。如果未找到该值,则返回 -1。indexOf 方法是区分大小写的
var myString = "brie, pepper jack, cheddar";
var myCapString = "Brie, Pepper Jack, Cheddar";
console.log('myString.indexOf("cheddar") is ' + myString.indexOf("cheddar"));
// logs 19
console.log('myCapString.indexOf("cheddar") is ' + myCapString.indexOf("cheddar"));
// logs -1
5、lastIndexOf()
方法返回调用String 对象的指定值最后一次出现的索引,在一个字符串中的指定位置 fromIndex处从后向前搜索。如果没找到这个特定值则返回-1 。字符串中的字符被从左向右索引。首字符的索引(index)是 0,最后一个字符的索引是 stringName.length - 1。
'canal'.lastIndexOf('a'); // returns 3 (没有指明fromIndex则从末尾l处开始反向检索到的第一个a出现在l的后面,即index为3的位置)
'canal'.lastIndexOf('a', 2); // returns 1(指明fromIndex为2则从n处反向向回检索到其后面就是a,即index为1的位置)
'canal'.lastIndexOf('a', 0); // returns -1(指明fromIndex为0则从c处向左回向检索a发现没有,故返回-1)
'canal'.lastIndexOf('x'); // returns -1
'canal'.lastIndexOf('c', -5); // returns 0(指明fromIndex为-5则视同0,从c处向左回向查找发现自己就是,故返回0)
'canal'.lastIndexOf('c', 0); // returns 0(指明fromIndex为0则从c处向左回向查找c发现自己就是,故返回自己的索引0)
'canal'.lastIndexOf(''); // returns 5
'canal'.lastIndexOf('', 2); // returns 2
6、match()
方法检索返回一个字符串匹配正则表达式的结果。
str.match(regexp)
regexp
一个正则表达式对象。如果传入一个非正则表达式对象,则会隐式地使用 new RegExp(obj) 将其转换为一个 RegExp 。如果你没有给出任何参数并直接使用match() 方法 ,你将会得到一 个包含空字符串的 Array :[""] 。
一个非正则表达式对象作为参数
var str1 = "NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript.",
str2 = "My grandfather is 65 years old and My grandmother is 63 years old.",
str3 = "The contract was declared null and void.";
str1.match("number"); // "number" 是字符串。返回["number"]
str1.match(NaN); // NaN的类型是number。返回["NaN"]
str1.match(Infinity); // Infinity的类型是number。返回["Infinity"]
str1.match(+Infinity); // 返回["Infinity"]
str1.match(-Infinity); // 返回["-Infinity"]
str2.match(65); // 返回["65"]
str2.match(+65); // 有正号的number。返回["65"]
str3.match(null); // 返回["null"]
7、padEnd()
方法会用一个字符串填充当前字符串(如果需要的话则重复填充),返回填充后达到指定长度的字符串。从当前字符串的末尾(右侧)开始填充。
'abc'.padEnd(10); // "abc "
'abc'.padEnd(10, "foo"); // "abcfoofoof"
'abc'.padEnd(6, "123456"); // "abc123"
'abc'.padEnd(1); // "abc"
8、padStart()
方法用另一个字符串填充当前字符串(如果需要的话,会重复多次),以便产生的字符串达到给定的长度。从当前字符串的左侧开始填充。
'abc'.padStart(10); // " abc"
'abc'.padStart(10, "foo"); // "foofoofabc"
'abc'.padStart(6,"123465"); // "123abc"
'abc'.padStart(8, "0"); // "00000abc"
'abc'.padStart(1); // "abc"
9、replace()
方法返回一个由替换值(replacement)替换部分或所有的模式(pattern)匹配项后的新字符串。模式可以是一个字符串或者一个正则表达式,替换值可以是一个字符串或者一个每次匹配都要调用的回调函数。如果pattern是字符串,则仅替换第一个匹配项。原字符串不会改变。
var re = /(\w+)\s(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2, $1");
// Smith, John
console.log(newstr);
10、slice()
方法提取某个字符串的一部分,并返回一个新的字符串,且不会改动原字符串。slice() 提取的新字符串包括beginIndex但不包括 endIndex
var str1 = 'The morning is upon us.', // str1 的长度 length 是 23。
str2 = str1.slice(1, 8),
str3 = str1.slice(4, -2),
str4 = str1.slice(12),
str5 = str1.slice(30);
console.log(str2); // 输出:he morn
console.log(str3); // 输出:morning is upon u
console.log(str4); // 输出:is upon us.
console.log(str5); // 输出:""
var str = 'The morning is upon us.';
str.slice(-3); // 返回 'us.'
str.slice(-3, -1); // 返回 'us'
str.slice(0, -1); // 返回 'The morning is upon us'
11、split()
方法使用指定的分隔符字符串将一个String对象分割成子字符串数组,以一个指定的分割字串来决定每个拆分的位置。
使用一个数组来作为分隔符
const myString = 'this|is|a|Test';
const splits = myString.split(['|']);
console.log(splits); //["this", "is", "a", "Test"]
const myString = 'ca,bc,a,bca,bca,bc';
const splits = myString.split(['a','b']);
// myString.split(['a','b']) is same as myString.split(String(['a','b']))
console.log(splits); //["c", "c,", "c", "c", "c"]
限制返回值中分割元素数量
var myString = "Hello World. How are you doing?";
var splits = myString.split(" ", 3);
console.log(splits);
12、substring()
方法返回一个字符串在开始索引到结束索引之间的一个子集, 或从开始索引直到字符串的末尾的一个子集。
var anyString = "Mozilla";
// 输出 "Moz"
console.log(anyString.substring(0,3));
console.log(anyString.substring(3,0));
console.log(anyString.substring(3,-3));
console.log(anyString.substring(3,NaN));
console.log(anyString.substring(-2,3));
console.log(anyString.substring(NaN,3));
// 输出 "lla"
console.log(anyString.substring(4,7));
console.log(anyString.substring(7,4));
// 输出 ""
console.log(anyString.substring(4,4));
// 输出 "Mozill"
console.log(anyString.substring(0,6));
// 输出 "Mozilla"
console.log(anyString.substring(0,7));
console.log(anyString.substring(0,10));
13、String.raw()
在大多数情况下, String.raw()是用来处理模版字符串的.
String.raw() 是唯一一个内置的模板字符串标签函数,因为它太常用了。不过它并没有什么特殊能力,你自己也可以实现一个和它功能一模一样的标签函数。
String.raw`Hi\n${2+3}!`;
// 'Hi\n5!',Hi 后面的字符不是换行符,\ 和 n 是两个不同的字符
String.raw `Hi\u000A!`;
// "Hi\u000A!",同上,这里得到的会是 \、u、0、0、0、A 6个字符,
// 任何类型的转义形式都会失效,保留原样输出,不信你试试.length
let name = "Bob";
String.raw `Hi\n${name}!`;
// "Hi\nBob!",内插表达式还可以正常运行
// 正常情况下,你也许不需要将 String.raw() 当作函数调用。
// 但是为了模拟 `t${0}e${1}s${2}t` 你可以这样做:
String.raw({ raw: 'test' }, 0, 1, 2); // 't0e1s2t'
// 注意这个测试, 传入一个 string, 和一个类似数组的对象
// 下面这个函数和 `foo${2 + 3}bar${'Java' + 'Script'}baz` 是相等的.
String.raw({
raw: ['foo', 'bar', 'baz']
}, 2 + 3, 'Java' + 'Script'); // 'foo5barJavaScriptbaz'