简体   繁体   中英

Regex to wrap all words in span, excluding img elements

I am trying to find a regex, in order to wrap all the words of a text in spans. I am using the following code:

$this.html($this.text().replace(
        /([^\s]*\s)/g, "<span>$1</span>"));

where this is referred to a div element. However, img and a elements, which are inside div, disappear. I tried to change the regex into:

$this.html($this.text().replace(
        /([^(\s | <a.*/a> | <img.*/img>)]*\s)/g, "<span>$1</span>"));

but i didn't fix the problem.

Can someone help me?

replace non-whitespace ( \\S ) where there is one or more ( + ) with a function, taking the match as a parameter.

 var str = 'Hello dear world <img src="https://placeholdit.imgix.net/~text?txtsize=60&txt=1&w=100&h=100"/> Hello dear world <img src="https://placeholdit.imgix.net/~text?txtsize=60&txt=1&w=100&h=100"/>'; function replaceThings(str) { var pre = "<span style='background-color:yellow'>"; var modString = str .replace(/\\S+/ig, function(word) { return pre + word + "</span>" }) .split(pre + "<img").join("<img") .split("/></span>").join("/>") .replace(/<img{1}.*?\\/>/ig, function (img){ return img.split(pre).join("").split("</span>").join("") }) return modString; } console.log( replaceThings(str) ); document.body.innerHTML = replaceThings(str) 

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