Andreas Köberle
Andreas Köberle

Reputation: 110922

JavaScript regex literal vs RegExp object

I came a long with this SO and would like to set the char count. Therefor I have to create the expresion as a String and use new RegExp(). So I change the the snippet a bit and use a new RegExp object

Orginal

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

//result:
"this is a longish"

With RegExp

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

//result:
"this is a longi"

As you can see the result of the second one is not the expected. Any hints whats the different between using a literal and using RegExp object here.

Upvotes: 2

Views: 346

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336198

In a string, you need to escape the backslashes:

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

(and you can use \S instead of [^\s]):

new RegExp('^(.{' + count + '}\\S*).*')

Upvotes: 6

Related Questions