Search code examples
javascriptjquerytrimspaces

Remove spaces from before and after a string inside a tag in a contenteditable div


I am trying to remove the spaces before and after string in a bold tag.

Functionalities: I have created a text editor in which when u type a text and select the text and press bold it will bold the text and when you press html button, it shows the html generated in the next window.

Issues faced: When i try to give tab space and then enter a text, and select the text along with the space and bold it, it bolds along with the empty space. Hence when i view the html in the html window i am able to see the space in the starting of the string. The code i used removes all spaces from the string , but i just want to trim the starting and beginning and still keep the spaces in between the string just like that. Any help will be much appreciated.

E.g: when u try to bold a string along with the space ' fdgfg gfdgfg fdgfg' , this is how it looks in the editor . The html generated looked like <b>&nbsp;&nbsp;fdgfg gfdgfg fdgfg</b> So i wrote a code which removes those space, but it removes all spaces and am left with <b>fdgfggfdgfgfdgfg</b>. but what i actually want is <b>fdgfg gfdgfg fdgfg</b> without spaces.

Script:

//shows the html
  $("#show-html").click(function(){      
    var html = $("#textEditor").html();      
    html = html.replace(/&nbsp;|\s/gi, '');
  });

DEMO:

P.S: It should delete only the starting and the ending white spaces, it should preserve the spaces in between the text. e.g " abcd efgh " this should be trimmed to "abcd efgh" the spaces in between text should not be removed.


Solution

  • One approach would be to iterate over each of the <b> elements, remove all the consecutive whitespace, and then trim the string.

    Updated Example

    $('#textEditor b').each(function () {
      $(this).text(function () {
        return $(this).text().replace(/\s+/g, ' ').trim();
      });
    });
    

    Simple input:

    "     this     is   a  string  "
    

    Output:

    <b>this is a string</b>