2

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.

Community
  • 1
  • 1
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297

1 Answers1

6

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*).*')
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561