Highlight Non-breaking spaces in HTML page or WordPress editor

When editing in WordPress, I sometimes use non-breaking spaces in the titles to keep the words together. When I save, there are no breaks there, but they look like regular spaces, so I can't see them. Also, WordPress creates non-breaking spaces when I type the body of my post, which I need to delete somehow.

I thought it would be easy to create a bookmarklet that uses jQuery to highlight uncompleted spaces in a web page or editor. However, I am not good with regexes, or maybe there is something else I am doing wrong. Here's the jQuery code:

    $('p').html($('p').html().replace(/ [\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]/g, '<span class="red">&nbsp;</span>'));

      

Here's a jFiddle: https://jsfiddle.net/y18e0c1w/

========

Maraka helped me here (see below). I created a bookmarklet with its code and added an empty space: nowrap to the range so you can still see the selection if it's at the end of the line. Here he is:
javascript:function%20escapeRegExp(e){return%20e.replace(/([.*+?^=!:${}()\]\[\/\\])/g,"\\$1")}function%20replaceAll(e){return%20e.string.replace(new%20RegExp(escapeRegExp(e.search),"g"),e.replace)}jQuery("body").html(replaceAll({string:jQuery("body").html(),search:"&nbsp;",replace:'<u%20style="background:#FF0;white-space:nowrap">%20</u>'}));

      

Remember that it relies on jQuery already loaded into the page. It doesn't play well with the WordPress backend, but it does work on the front-end, which is good for me right now. Hope someone else finds this helpful.

+3


source to share


1 answer


Got this: https://jsfiddle.net/y18e0c1w/2/

function escapeRegExp(s) {
    return s.replace(/([.*+?^=!:${}()\]\[\/\\])/g, '\\$1');   
}

function replaceAll(p) {
 return p['string'].replace(new RegExp(escapeRegExp(p['search']), 'g'), p['replace']);   
}

$('p').html(
    replaceAll({
        string: $('p').html(),
        search: '&nbsp;',
        replace: '<span class="red"> </span>'
    })
);

      

The first two functions are just helper functions. Then I replace &nbsp;

the span with what it is.



Note that I used normal space in between, because then there is no problem with re-execution. Otherwise, you will wrap spans around &nbsp;

each output.

A quick and dirty full body solution: https://jsfiddle.net/y18e0c1w/7/

0


source







All Articles