0

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?

themis93
  • 119
  • 1
  • 9
  • Check http://stackoverflow.com/questions/20689220/wrap-character-in-string-excluding-a-link-tag-with-javascript-regex – Wiktor Stribiżew Nov 10 '16 at 09:36
  • you try to wrap text only?give sample of html mark up – guradio Nov 10 '16 at 09:37
  • 2
    If you want to act only on the words of text and not on elements, you need to process only text nodes. jQuery only offers a small number of things that work at the text node level, including the [`contents`](http://api.jquery.com/contents) function which returns all of the nodes (not just elements) in a container. You can then loop over it with `each`, replacing just the text nodes with spans. You'll need to use DOM methods for part of this, such as `insertBefore`. It's non-trivial, but not *hard*. I don't have time to whip up a reasonable demo, though, so posting as a comment. – T.J. Crowder Nov 10 '16 at 09:42

1 Answers1

-2

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)
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28
  • thank you so much for your answer. i am using /([^\s]*\s)/g instead of /\S+/ig, because the text is in the greek language. – themis93 Nov 10 '16 at 10:10