js 查找字符串中指定字符 模糊查询 不区分大小写

2022年10月22日12:13:39

js  查找特定字符 模糊查询  不区分大小写

  var str = "hello  world ! hello  coder!" ;
  //查找‘HELLO’是否存在,找不到返回null
  var reg = new RegExp('HELLO','i') ;
  var isHas = str.match(reg);
  console.log(isHas); 
  //打印结果: ["hello", index: 0, input: "hello  world ! hello  coder!", groups: undefined]
var str="Hello world!";
//查找"Hello"
var patt=new RegExp('HELLO','i') ;
var result=patt.test(str);
console.log(result) // true

如上两种,用正则new RegExp,test/match查找可以实现,不区分大小写

js 查找字符串中是否包含指定的字符串

1、indexOf()

var str = "123";
console.log(str.indexOf("3") != -1 ); // true

indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。如果要检索的字符串值没有找到,则该方法返回 -1

2、includes()

var str = "Hello world, welcome to the Runoob。";
var n = str.includes("world"); //true

includes() 方法用于判断字符串是否包含指定的子字符串,如果找到匹配的字符串则返回 true,否则返回 false。注意: includes() 方法区分大小写。

3、search()

var str="Visit W3School!"
console.log(str.search(/W3School/)) //6

var str="Visit W3School!"
console.log(str.search('W3School')) //6

search() 方法用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串。如果匹配到字符串则返回,字符串所在索引。

4、match()

var str="The rain in SPAIN stays mainly in the plain";
var n=str.match(/ain/g); // ain,ain,ain

match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。注意: includes() 方法不区分大小写。

5、test()

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
    console.log("移动")
} else {
    console.log("PC")
}

var str="Hello world!";
//查找"Hello"
var patt=/Hello/g;
var result=patt.test(str);
console.log(result) // true

test() 方法用于检测一个字符串是否匹配某个模式。如果字符串中有匹配的值返回 true ,否则返回 false。

6、exec()

var str="Hello world!";
//查找"Hello"
var patt=/Hello/g;
var result=patt.exec(str);
console.log(result) // Hello

exec() 方法用于检索字符串中的正则表达式的匹配。如果字符串中有匹配的值返回该匹配值,否则返回 null。

  • 作者:小猫儿
  • 原文链接:https://blog.csdn.net/zhengyinling/article/details/111587670
    更新时间:2022年10月22日12:13:39 ,共 1495 字。