2

Ok, I've spent multiple hours on this issue. I've got some javascript that needs to split a string before a word after a certain amount of characters. So far, I've come up with a solution, but this behaves strangely.
Look at this example:

var text1 = "Apple MacBook 12” Retina 2016 Spacegray (MLH82N/A)";
var text2 = "Apple MacBook 12” Retina 2016 Spacegray (MLH82N/A)";
var regex1 = /.{24}\S*(\s|-)+/gi;
var regex2 = new RegExp(".{24}\S*(\s|-)+",'gi');
//var res1 = text1.replace(regex1, "$&@").split('@').join("\n").replace("\n", "<br>");
//var res2 = text2.replace(regex2, "$&@").split('@').join("\n").replace("\n", "<br>");
var res1 = text1.replace(regex1, "$&@");
var res2 = text2.replace(regex2, "$&@");

console.log(res1);
console.log(res2);

regex1 gives the wanted result, but the number 24 in the regex needs to be a variable, which makes it impossible to use regex1 because that doesn't support variables.

If anyone can point me in the right direction. I would be forever thankful!

Edit: the marked duplicate I have read, but the problem is that the 'exact' regex doesn't output the same result. The RexExp-object is the weird one.

Answer:

As the total noob I am, I forgot to escape the backslashes in the RegExp-object.
Look at this working code while I go cry in a corner...

var text1 = "Apple MacBook 12” Retina 2016 Spacegray (MLH82N/A)";
var text2 = "Apple MacBook 12” Retina 2016 Spacegray (MLH82N/A)";
var regex1 = /.{24}\S*(\s|-)+/gi;
var regex2 = new RegExp(".{24}\\S*(\\s|-)+",'gi');
//var res1 = text1.replace(regex1, "$&@").split('@').join("\n").replace("\n", "<br>");
//var res2 = text2.replace(regex2, "$&@").split('@').join("\n").replace("\n", "<br>");
var res1 = text1.replace(regex1, "$&@");
var res2 = text2.replace(regex2, "$&@");

console.log(res1);
console.log(res2);
Community
  • 1
  • 1
L00_Cyph3r
  • 458
  • 2
  • 11
  • Something like `new RegExp(\`.{${num}}\\S*[\\s-]+\`,'gi')` where `num` is the dynamic number value. – Wiktor Stribiżew Oct 07 '16 at 10:54
  • 2
    *The RexExp-object is the weird one.*: Yes, because you make another very common mistake, the backslashes must be doubled in the RegExp constructor. See http://stackoverflow.com/questions/10769964/backslashes-regular-expression-javascript – Wiktor Stribiżew Oct 07 '16 at 10:56
  • "Look at this working code while I go cry in a corner..." made my day :) – Lajos Arpad Oct 07 '16 at 12:11

0 Answers0