JavaScript String Multiline Trim/Cleanup

πŸ‘‹ Ciprian on Friday, September 15, 2017 in Blog
Last modified on Friday, September 15, 2017

Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

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

JavaScript

/*
 * 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(', ,', ',')
            .trim();
};

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

Usage

// jQuery
$('#myElement').text().allTrim();
$('#myElement').text().allCommas();

// JavaScript
document.getElementById('myElement').innerText.allTrim();
document.getElementById('myElement').innerText.allCommas();

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. Last modified on Friday, September 15, 2017.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Privacy Policy