JavaScript String Multiline Trim/Cleanup

This small JavaScript prototypes enhance the trim() function and allow for better trimming and/or replacing line breaks with commas (or any other character).


 * Prototype function to remove all double whitespaces and preceding line breaks
String.prototype.allTrim = String.prototype.allTrim || function() {
    return this
            .replace(/  +/g, ' ')
            .replace(/\n\s*\n/g, '\n')
            .replace(/(\r\n|\n|\r)/gm, '') // Remove all 3 types of line breaks
            .replace(/^,+/, '')
            .replace(', ,', ',')

 * Prototype function to replace all line breaks with commas
String.prototype.allCommas = String.prototype.allCommas || function() {
    return this
            .replace(/(\r\n|\n|\r)/gm, ', ')


// jQuery

// JavaScript

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Added by Ciprian on Friday, September 15, 2017 in Blog

Unlimited Automated Page Speed Monitoring & Tracking.
Use SpeedFactor to track your website. It’s simple and reliable.
See how real people experience the speed of your website. Then find (and fix) your web performance problems.
Get Started

Related Articles

Privacy Policy