Useful JavaScript String Prototypes

Follow me!

If you like this article, go ahead and follow me on Twitter:

Follow @getButterfly

This is a function to remove all double whitespaces and preceding line breaks.

/**
 * 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();
};

// Usage:
// string.allTrim();

This is a function to replace all line breaks with commas.

/**
 * 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:
// string.allCommas();

Enjoy!

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

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

👋 Added by Ciprian on Monday, April 16, 2018 in Blog, JavaScript. Last modified on Thursday, May 24, 2018.

Contribute!

Contribute to this article by sharing your opinion on Twitter:

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
Privacy Policy