学习在 JavaScript 中获取字符串的两个字符之间的子字符串的多种方法。
1. String substring(), indexOf() 和 lastIndexOf() 方法
要在 JavaScript 中获取字符串的两个字符之间的子字符串,请在字符串上调用 slice() 方法,将个字符次出现之后的索引作为个参数传递,并将后一次出现的索引传递给 第二个字符作为第二个参数。 例如:
functiongetSubstring(str, char1, char2){returnstr.substring( str.indexOf(char1) +1, str.lastIndexOf(char2) ); }conststr1 =one:two;three;constsubstr1 = getSubstring(str1,:,;);console.log(substr1);// twoconst str2 = one?two!three;constsubstr2 = getSubstring(str2,?,!);console.log(substr2);// twoString indexOf() 方法返回值在字符串中次出现的位置。 另一方面,lastIndexOf() 返回值在字符串中后一次出现的位置。
String substring() 方法返回开始和结束索引之间的字符串部分,分别由个和第二个参数指定。 我们将 1 添加到 indexOf() 的结果中,因为我们不希望个字符包含在我们试图获取的子字符串中。 但是,我们不需要从 lastIndexOf() 的结果中减去 1,因为 substring() 已经排除了指定结束索引处的字符。
如果字符串中不存在该值,则 indexOf() 和 lastIndexOf() 都将返回 -1。 这意味着当字符串中不存在个字符时,从开始到后出现第二个字符的所有字符串都将包含在字符串中。
conststr1 =one:two;three;constsubstr1 = getSubstring(str1,–,;);console.log(substr1);// one:two此外,当第二个字符不存在时,从个字符开始到次出现的所有字符串都将包含在字符串中。
conststr1 =one:two;three;constsubstr1 = getSubstring(str1,:,–);console.log(substr1);// one根据我们的用例,这可能不是我们想要的。 如果我们希望在任一字符不存在时返回一个空字符串 (),我们需要显式检查这一点:
functiongetSubstring(str, char1, char2){constchar1Index = str.indexOf(char1);constchar2Index = str.lastIndexOf(char2);if(char1Index ===-1)return;if(char2Index ===-1)return;returnstr.substring(char1Index, char2Index); }conststr1 =one:two;three;constsubstr1 = getSubstring(str1,–,;);console.log(substr1);// (empty string)const substr2 = getSubstring(str1, :, -);console.log(substr2);// (empty string)2. String split()、Array slice() 和 Array join() 方法
这是另一种获取字符串的两个字符之间的子字符串的方法:
functiongetSubstring(str, char1, char2){returnstr .split(char1) .slice(1) .join() .split(char2) .slice(0,-1) .join(); }conststr1 =one:two;three;constsubstr1 = getSubstring(str1,:,;);console.log(substr1);// twoconst str2 = one?two!three;constsubstr2 = getSubstring(str2,?,!);console.log(substr2);// twoString split() 方法使用指定的分隔符分割字符串。
const str1 =one:two;three;//[one,two;three]console.log(str1.split(:));Array slice() 方法提取数组的开始和结束索引之间的元素,这些元素分别由个和第二个参数指定。 我们将 1 作为个参数传递而没有指定第二个参数,因此 slice() 从索引 1 处的元素提取到字符串的末尾。
//[two;three];console.log([one,two;three].slice(1));我们在 slice() 的结果上调用 Array join() 方法,将数组的元素连接成一个字符串。
conststr1 =one:two;three;// two;threeconsole.log([two;three].join());我们再次分割这个结果,这次是第二个字符。
//[two,three];console.log(two;three.split(;));我们在此拆分产生的数组上调用 slice(),将 0 和 -1 作为参数传递,以将除后一个之外的所有数组元素复制到新数组中。
//[two]console.log([two,three].slice(0,-1));后,我们在这个结果上调用 join() 来获取两个字符之间的字符串。
与种方法不同,这种方法通过返回一个空字符串来处理其中一个字符不在字符串中的情况。
functiongetSubstring(str, char1, char2){returnstr .split(char1) .slice(1) .join() .split(char2) .slice(0,-1) .join(); }const str1 =one:two;three; const substr1 = getSubstring(str1,–,;); console.log(substr1); //(emptystring)const substr2 = getSubstring(str1,:,–); console.log(substr2); //(emptystring)关注七爪网,获取更多APP/小程序/网站源码资源!