Search code examples
jqueryprependouterhtml

Trim spaces from link beginning, and prepend space to outside of A tag


I have an author on our blog who mistakenly puts spaces inside the links all the time, so each link starts with an underlined space. This is very annoying. I've attempted to fix this via jquery with the following code, but can't seem to unlink the initial space AND add a non linked space above the HMTL A element.

    text = $(this).text();
    if (text[0] == ' ') {
        console.log(this);
        $(this).text($.trim( $(this).text() ));
        // theHTML = $(this).outerHTML();
        $(this).outerHTML().replaceWith('=' + $(this).outerHTML());
        // $(this).prepend('=');
    }

example: http://jsfiddle.net/691tx33w/

If we remove the space, the word and the link get smushed together.


Solution

  • used .trim() to remove spaces and .before() to add the space before the <a> tag

    $(document).ready(function() {
        $('a').each(function() {        
            if ($(this).text().charAt(0) == ' ') {
                $(this).text($.trim($(this).text()));
                $(this).attr('href', $.trim($(this).attr('href')));
                $(this).before(' ');
            }
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p>My wife and I live in southern Florida where, according to<a title="1.1 Million U.S. Properties with Foreclosure Filings in 2014, Down 18 Percent From 2013 to Lowest Level Since 2006" href="http://www.realtytrac.com/news/foreclosure-trends/1-1-million-u-s-properties-with-foreclosure-filings-in-2014-down-18-percent-from-2013-to-lowest-level-since-2006/" target="_blank"> one report</a>, 27% of homes have seen a foreclosure notice since 2007. In other places the numbers aren’t as bad, but they’re still depressing. What happened? Sure, times were tough, but even when<a title="unemployment topped 10%" href="http://www.nytimes.com/2009/11/07/business/economy/07jobs.html?_r=0" target="_blank"> unemployment topped 10%</a>, that left about 90% of us employed.</p>