4

I'm trying to find and replace all white spaces in a html file. Here's my code so far:

html.replace(@ (?![^<]*>|[^<>]*</)@g,"&nbsp;") 

But above expression throws error as not a valid expression. How do I make it work?

1
  • 2
    Use / to delimit regex literals. Commented Jun 1, 2019 at 8:55

1 Answer 1

3

Regexes are delimited by /, not @.

html.replace(/ (?![^<]*>|[^<>]*<\/)/g,"&nbsp;") 

Here's another regex that literally replaces every white space with a non-breaking space:

html.replace(/\s+/g, "&nbsp;"); 
Sign up to request clarification or add additional context in comments.

4 Comments

I see. I tought it works as same as php do. And how about expression. Still its not converts white spaces into the &nbsp ?
@TeomanTıngır Did you re-add the space that Jack inadvertently removed? I just edited it back in. Also, do you assign the result of replace() to a variable? Please provide a minimal reproducible example.
Whoops, sorry @melpomene.
@melpomene yes I did. I also kinda forgot to mentioned that I dont want to remove white spaces inside of the html tags. Because if there are tag attributes, it breaks html and makes it unreadable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.