简体   繁体   中英

Javascript regex: remove space(s) if not surrounded by a letter

I'm trying to clean some html text with javascript, there are white spaces included before and after some words (text is poorly formatted).

Currently I have this regex:

$("#" + target + " *").replaceText(/([\S][\u05B0-\u05C4]*)/gi, '<span class="marked">$1<\/span>');

This will capture all the non white-space characters and wrap them in a span element, but will not capture spaces between words (I need the span).

How would you solve this?

This will match multiple repeated (spaces) and replace them with a single space:

'Quick   Brown      Fox'.replace(/[ ]+/g, ' '); //returns 'Quick Brown Fox'

This will match multiple repeated \\n\\r\\t (whitespace symbols - spaces, tabs, new-lines and line-breaks) and replace them with a single space:

'Quick     Brown    Fox'.replace(/\s+/g, ' ');  //returns 'Quick Brown Fox'

Fiddled

I don't understand your explanation of what you're trying to achieve with span wraparounds, but you can do whatever you want with the output from above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM