5

利用js判断字符串中是否包含某个字符串的方法

 2 years ago
source link: https://www.huhexian.com/30904.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

利用js判断字符串中是否包含某个字符串的方法

2022-03-0909:47:23评论932字

JS检测一个字符串中是否包含某个特定字符串,有多种检测方法,下面就来详细的说一下。

js判断字符串中是否包含某个字符串

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

  1. var str = "feiniaomy.com";
  2. if(str.indexOf("niao") != -1){
  3. console.log('包含');
  4. }else{
  5. consloe.log('不包含');
  6. //输出结果:包含

js search() 方法用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串。如果没有找到任何匹配的子串,则返回 -1。

  1. var str = "feiniaomy.com";
  2. if(str.search("niao") != -1){
  3. console.log('包含');
  4. }else{
  5. consloe.log('不包含');
  6. //输出结果:包含

js match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配.

  1. var str = "feiniaomy.com";
  2. var reg = RegExp(/niao/);
  3. if(str.match(reg)){
  4. console.log('包含');
  5. }else{
  6. consloe.log('不包含');
  7. //输出结果:包含

js test() 方法用于检索字符串中指定的值,如果找到返回 TRUE 如未找到返回 FALSE

  1. var str = "feiniaomy.com";
  2. var reg = RegExp(/niao/);
  3. if(reg.test(str)){
  4. console.log('包含');
  5. }else{
  6. consloe.log('不包含');
  7. //输出结果:包含

js exec() 方法用于检索字符串中的正则表达式的匹配。返回一个数组,其中存放匹配的结果。如果未找到匹配,则返回值为 null。

  1. var str = "feiniaomy.com";
  2. var reg = RegExp(/niao/);
  3. if(reg.exec(str)){
  4. console.log('包含');
  5. }else{
  6. consloe.log('不包含');
  7. //输出结果:包含

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK