一些查找子字符串的方法~

160 阅读3分钟

查找字符串

str.indexOf

第一个方法是 str.indexOf(substr, pos)

它从给定位置 pos 开始,在 str 中查找 substr,如果没有找到,则返回 -1,否则返回匹配成功的位置。

image.png

按位(bitwise)NOT 技巧

这里使用的一个老技巧是 bitwise NOT~ 运算符。它将数字转换为 32-bit 整数(如果存在小数部分,则删除小数部分),然后对其二进制表示形式中的所有位均取反。

实际上,这意味着一件很简单的事儿:对于 32-bit 整数,~n 等于 -(n+1)

alert( ~2 ); // -3,和 -(2+1) 相同 
alert( ~1 ); // -2,和 -(1+1) 相同 
alert( ~0 ); // -1,和 -(0+1) 相同 
alert( ~-1 ); // 0,和 -(-1+1) 相同

正如我们看到这样,只有当 n == -1 时,~n 才为零(适用于任何 32-bit 带符号的整数 n)。

因此,仅当 indexOf 的结果不是 -1 时,检查 if ( ~str.indexOf("...") ) 才为真。换句话说,当有匹配时。

let num = 520; 
if (~num.indexOf(520)) {
alert( '找到!' ); // 正常运行 
}

这种方法被淘汰了,因为不是以显而易见的方式使用语言特性 我们有新的方法即:.includes方法

Array.prototype.includes()

includes()  方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false

语法:

includes(searchElement, fromIndex)

searchElement :需要查找的元素值 fromIndex:从fromIndex索引处开始查找searchElement,默认为 0。

🐱‍👓使用 includes() 比较字符串和字符时是区分大小写的。

返回一个布尔值 Boolean 。 如果在数组中(或 fromIndex 指定的范围中)找到了 searchElement,则返回 true,否则返回 false

alert( "Widget with id".includes("Widget") ); // true alert( "Hello".includes("Bye") ); // false
alert( "Widget".includes("id") ); // true 
alert( "Widget".includes("id", 3) ); // false, 从位置 3 开始没有 "id"

获取子字符串

JavaScript 中有三种获取字符串的方法:substringsubstr 和 slice

slice(start, end)

返回字符串从 start 到(但不包括)end 的部分。

let str = "stringify"; 
alert( str.slice(0, 5) ); // 'strin',从 0 到 5 的子字符串(不包括 5) 
alert( str.slice(0, 1) ); // 's',从 0 到 1,但不包括 1,所以只有在 0 处的字符

如果没有第二个参数,slice会一直运行到字符串末尾

start/end 也有可能是负值。它们的意思是起始位置从字符串结尾计算:

  let str = "15616113";
    console.log(str.slice(-1));//3
    console.log(str.slice(-2));//13
    console.log(str.slice(-6));//616113
     console.log(str.slice(-6,-2));//6161
    console.log(str.slice(-6,-1));//61611,从右边第六个开始到右边第一个结束'

substring() 

substring()  方法返回一个字符串在开始索引到结束索引之间的一个子集,或从开始索引直到字符串的末尾的一个子集。

str.substring(indexStart[, indexEnd])

indexStart 需要截取的第一个字符的索引,该索引位置的字符作为返回的字符串的首字母。

indexEnd 可选。一个 0 到字符串长度之间的整数,以该数字为索引的字符不包含在截取的字符串内。

返回字符串从 start 到(但不包括)end 的部分。

这与 slice 几乎相同,但它允许 start 大于 end

let str = "st*ring*ify"; // 这些对于 substring 是相同的 alert( str.substring(2, 6) ); // "ring" 
alert( str.substring(6, 2) ); // "ring" 
// ……但对 slice 是不同的: 
alert( str.slice(2, 6) ); // "ring"(一样) 
alert( str.slice(6, 2) ); // ""(空字符串)

不支持负参数(不像 slice),它们被视为 0

substr

目前还没被废弃,但是不推荐使用,建议使用substring

详情请参考String.prototype.substr()


本文参考资料:字符串 (javascript.info)

String.prototype.substring() - JavaScript | MDN (mozilla.org)