Using Regular Expression to Truncate a String

what’s happening:
I try to use regular expression to solve the truncate a string assignment, but there seems to have something wrong with the regular expression.

My code so far

function truncateString(str, num) {
//let regex = /(?=^.{num}).+/, while num is the given parameter: 
 let regex = new RegExp("/(?=^.{" + num + "}).+/");                            
  return str.replace(regex, "...");

console.log(truncateString("A-tisket a-tasket A green and yellow basket", 8));

The return is always the whole str without any “…” at the end.

I tried to examine it by replacing the num variable into number 8(which is in the example), the return in the console shows “…”, seems like the regexp didn’t match the expected substring.

let regex = /(?=^.{8}.+)/;

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36.

Link to the challenge:

Why would you want to use regex for this kind of problem?

What exactly do you think this regex is doing?

In this instance it might be less of a headache instead of str.replace(), use str.match() then concat your “…”. Even then you would still have to add a catch for num values equal to or greater than the string length.

As for your regex it appears you are using positive lookahead incorrectly. Positive lookahead should follow the main expression, not be the main expression.

let regex = /\d(?=px)/g;  /*this looks for any digit followed by px*/
let str = "1pt 2px 3em 4px";
return str.match(regex); /*this will match 2 and 4 but not 1 or 3*/

Also when creating a new regex class you can exclude “/” at the beggining and the end as this is added automatically.

let num = 8;
let regex = new RegExp("(?=^.{" + num + "}).+");
return regex; /* this will return "/(?=^.{8}).+/" */

You should avoid regex for the challenge and convert this string into an array instead.

edit: removed solution posted