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.

0

1 Answer 1

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*).*')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.