Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

443
Views
Wrapping text in Javascript - Need help using existing good answer

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!