Javascript RegExp和边界 [英] Javascript RegExp and boundaries

查看:52
本文介绍了Javascript RegExp和边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个同事问我关于正则表达式的问题,我似乎找不到他的答案.

A colleague asked me about a Regular expression problem, and I can't seem to find and answer for him.

我们在文本编辑器中使用边界突出显示某些长度的文本,但是下面的示例代码显示了该问题:

We're using boundaries to highlight certain lengths of text in a text editor, but here's some sample code that shows the problem:

<script type="text/javascript">
var str = "Alpha , Beta, Gamma Delta Epsilon, AAlphaa, Beta Alpha<br/>";
var rx = new RegExp('\bAlpha\b','gim');

document.write(str.replace(/\b(Alpha)\b/gim, '-- $1 --'));
document.write(str.replace(rx, '== $1 =='));
</script>

问题是,第一个文字str.replace有效,但RegExp选项无效.

The issue is, the first literal str.replace works, but the RegExp option doesn't.

我在IE和FF中有相同的行为,有人知道为什么吗?

I've got the same behaviour in IE and FF, anyone know why ?

推荐答案

我猜测它不起作用,因为您需要对传递给RegExp的字符串中的反斜杠进行转义.你有这个:

I'm guessing it doesn't work because you need to escape the backslashes in your string that you pass to RegExp. You have this:

var rx = new RegExp('\bAlpha\b','gim');

您需要这个:

var rx = new RegExp('\\bAlpha\\b','gim');

传递给RegExp的字符串中包含2个退格字符,因为 \ b 是用于在字符串中插入退格的转义序列.您需要用另一个反斜杠来使每个反斜杠转义.

The string you passed to RegExp has 2 backspace characters in it, since \b is the escape sequence for inserting a backspace into a string. You need to escape each backslash with another backslash.

这篇关于Javascript RegExp和边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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