SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Jun 2008
    0 Post(s)
    0 Thread(s)

    Arrow Trim and format plain text

    I have the following script that converts line breaks from plain text into HTML formatted paragraphs. It takes plain text from one text area field and outputs the new formatted text into another text area field.

    function convertText(){
    var noBreaks = document.getElementById("oldText").value;
    noBreaks = noBreaks.replace(/\r\n/g,"[-LB-]");
    re4 = /\[-LB-\]\[-LB-\]/gi;
    noBreaks = noBreaks.replace(re4,"</p><p>");
    re5 = /\[-LB-\]/gi;
    noBreaks = noBreaks.replace(re5," ");
    noBreaks ='<p>'+noBreaks+'</p>';
    noBreaks = noBreaks.replace(/<\/p><p>/g,"</p>\r\n\r\n<p>");
    document.getElementById("newCode").value = noBreaks;
    <textarea id="oldText" name="oldText" rows="12" cols="90"></textarea>
    <textarea id="newCode" name="newCode" rows="12" cols="90"></textarea>
    <input type="button" value="Convert" onclick="javascript:convertText()">
    1. How can I trim/filter all double-spaces, triple-spaces, and so on? I only want single spaces to exist. Plus, is there a way to remove these spaces from the very begininng and end of each paragraph?

    2. Secondly, if there's a space (not a line break or carriage return) between each paragraph, it merges the two paragraphs together, instead of creating two separate paragraphs. Is there a way to fix this?


  2. #2
    SitePoint Member
    Join Date
    Feb 2009
    0 Post(s)
    0 Thread(s)
    Good old regular expressions.

    noBreaks.replace(/( ){2,}/g," ") Replaces 2 or more consecutive spaces with a single space.

    Check out this great Regex tester/tool - design215[dotcom] toolbox regexp [dot PHP]


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts