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.