检查文本是否在字符串中 [英] Check if text is in a string

查看:59
本文介绍了检查文本是否在字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查是否有一些文字在字符串中,例如我有一个字符串

I want to check is some text is in a string for instance i have a string

str = "car, bycicle, bus"

我有另一个字符串

str2 = "car"

我想检查是否str2在str。

I want to check if str2 is in str.

我是javascript的新手所以请耐心等待:):

I am a newbie in javascript so please bear with me :)

问候

推荐答案

if(str.indexOf(str2) >= 0) {
   ...
}

或者如果你想进入正则表达式路线:

Or if you want to go the regex route:

if(new RegExp(str2).test(str)) {
  ...
}

但是在后者中你可能会遇到转义(元字符)的问题,所以第一条路线更容易。

However you may face issues with escaping (metacharacters) in the latter, so the first route is easier.

这篇关于检查文本是否在字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆