字词边界与JavaScript的开头或结尾不匹配 [英] Word boundary won't match the beginning or end in Javascript

查看:60
本文介绍了字词边界与JavaScript的开头或结尾不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此代码,我得到了意想不到的结果:

I'm getting unexpected results with this code:

'foo'.match(new RegExp('\bfoo\b')); // Returns null

为什么在返回"foo"时却返回 null ?

Why is this returning null while this one returns "foo"?

'foo'.match(new RegExp('foo')); // Returns "foo"

单词边界标记也不匹配开头和结尾吗?

Doesn't a word boundary marker match the beginning and end as well?

我需要正则表达式本身为字符串,因为我正在向其中注入变量.

I need the regular expression itself to be a string because I am injecting variables into it.

推荐答案

转义反斜杠

'foo'.match(new RegExp('\\bfoo\\b'));

这篇关于字词边界与JavaScript的开头或结尾不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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