• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

353
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 3 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 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error