I want to wrap simple text in a <span>
object by getting its innerText (which I can do) and replacing it with text that has been wrapped even if only with \n
used in place for new lines.
I've found this answer But there wasn't an example provided of how to use it.
// Static Width (Plain Regex)
const wrapFuntion = (s) => s.replace(
/(?![^\n]{1,32}$)([^\n]{1,32})\s/g, '$1\n'
);
Lets say my string is defined as below
let stringName = "Here is my really long string, that I want to wrap every 20 or so characters"
let maxChars = 20; // Max number of characters on each line
let newString = wrapFuntion(stringName, maxChars);
From the comments on the answer it's probably easy for anyone with JavaScript experience, or I've missed something most find obvious in the answer. Just looking to learn.
my score is too low to comment on original answer
Use the code right below the static code, the one that says dynamic code
// Dynamic Width (Build Regex)
const wrap = (s, w) => s.replace(
new RegExp(`(?![^\\n]{1,${w}}$)([^\\n]{1,${w}})\\s`, 'g'), '$1\n'
);
since you want to specify the line length.
// Dynamic Width (Build Regex)
const wrap = (s, w) => s.replace(
new RegExp(`(?![^\\n]{1,${w}}$)([^\\n]{1,${w}})\\s`, 'g'), '$1\n'
);
const bob = document.getElementById("bob");
let stringName = bob.innerText;
let wrapNum = 20;
let newString = wrap(stringName, wrapNum);
bob.innerText = newString;
<span id="bob">Here is my really long string, that I want to wrap every 20 or so characters</span>