Lets say you have an HTML string like this:
<div id="loco" class="hey" >lorem ipsum pendus <em>hey</em>moder <hr /></div>
And need to place <br/> elements after every space character…. which I was doing with:
HTMLtext.replace(/\s{1,}/g, ' <br/>');
However, the problem is that this inserts breaks after space characters in-between tags (between tag properties) too and I’d of course like to do this for tag textual contents only. Somehow I was always really bad with regular expressions – could anyone help out?
So basically do my original whitespace match but only if its not between < and > ?
Regex is not a good tool for this. You should be working with the DOM, not with the raw HTML string.
For a quick-and-dirty solution that presupposes that there are no
<or>character in your string except those delimiting a tag, you can try this, though:This inserts a
<br/>after whitespace only if the next angle bracket is an opening angle bracket.Explanation:
Replace that with
$&(which contains the matched characters) plus<br/>.This regex does not check if there is a
>further behind, as this would require a positive look*behind* assertion, and JavaScript does not support these. So you can’t check for that, but if you control the HTML and are sure that the conditions I mentioned above are met, that shouldn’t be a problem.