2

我很喜欢这个SO,想设置字符数。因此,我必须将表达式创建为 String 并使用new RegExp(). 所以我稍微改变了片段并使用了一个新RegExp对象

原件

var t = "this is a longish string of text";
t.replace(/^(.{11}[^\s]*).*/, "$1");

//result:
"this is a longish"

使用正则表达式

var t = "this is a longish string of text";
var count = 11;
t.replace(new RegExp('^(.{' + count + '}[^\s]*).*'), "$1");

//result:
"this is a longi"

如您所见,第二个结果不是预期的。任何提示在这里使用文字和使用 RegExp 对象有什么不同。

4

1 回答 1

6

在字符串中,您需要转义反斜杠:

new RegExp('^(.{' + count + '}[^\\s]*).*')

(您可以使用\S代替[^\s]):

new RegExp('^(.{' + count + '}\\S*).*')
于 2012-09-13T06:50:04.630 回答