0

HTML

<h3>Original String</h3>
    <pre class="original">      Paragraph of text with       multiple    white   spaces before and after.       </pre>
    <br>
 <h3>Trimmed String</h3>
 <pre class="trimmed"></pre>

JQuery

$(document).ready(function(){
        var myStr = $(".original").text();
        var trimStr = $.trim(myStr);
        trimStr = trimStr.replace(/[\r\n]+/g, "");
        $(".trimmed").html(trimStr);
    });

The above code is trimming start and end of paragraph but not between. The output is:

Paragraph of text with       multiple    white   spaces before and after.

I want the output to be

Paragraph of text with multiple white spaces before and after.

Here is my JS Fiddle: https://jsfiddle.net/n5t3cse1

What am I doing wrong? Please suggest. Thanks!

1
  • Why are you using the <pre> tag instead of the <p> tag? Commented Aug 12, 2020 at 13:09

4 Answers 4

2

You could get this done using a single line.

$(document).ready(function(){
  $(".trimmed").html($(".original").text().replace(/\s+/g,' ').trim())
});

The regex finds any sequential spaces and replace() function replaces them by a single space. Trim() is used to remove white spaces from start and end of string.

Sign up to request clarification or add additional context in comments.

1 Comment

This answer could be improved by explaining what the regex you added does.
1

Replace two or more space characters with a single space by using regex.

$(document).ready(function() {
  var myStr = $(".original").text();
  var trimStr = myStr.replace(/ {2,}/g, ' ').trim();
  $(".trimmed").html(trimStr);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Original String</h3>
<pre class="original">      Paragraph of text with       multiple    white   spaces before and after.       </pre>
<br>
<h3>Trimmed String</h3>
<pre class="trimmed"></pre>

Comments

1

After trimming the string, you could replace any sequence of more than one space with a single space:

trimStr = trimStr.replace(/\s{2,}/g, " ");

Comments

0

You can run a loop to remove the double spaces until no double space is found.

$(document).ready(function(){
        var myStr = $(".original").text();
        var trimStr = $.trim(myStr);
        while(trimStr.indexOf('  ')!=-1)
          trimStr = trimStr.replace('  ', '');
        $(".trimmed").html(trimStr);
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Original String</h3>
    <pre class="original">      Paragraph of text with       multiple    white   spaces before and after.       </pre>
    <br>
 <h3>Trimmed String</h3>
 <pre class="trimmed"></pre>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.