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);