scader
scader

Reputation: 525

Match and replace a string using JavaScript regex

EDIT Not a duplicate question. This details the ability to use a function, not a string, to process the replaced strings.

I need to extract regex matched results then replace them with an empty string. If I use match, then it doesn't perform the replace, and if I use replace, it doesn't return the content matched. Is it possible to do both in one, or is that always a two-step process?

For example, I need to extract all the tags out of an HTML string, save it for processing separately, and replace it with an empty string.

var html = "This is HTML<br><style>#a{}</style>This is more HTML.<style>#b{}</style>.

I can process the span tags immediately, or later if they're all returned at together.

Upvotes: 1

Views: 1843

Answers (1)

georg
georg

Reputation: 214949

It goes like this:

   > html = "This is HTML<br><style>#a{}</style>This is more HTML.<style>#b{}</style>"
   > tags = []
   > html.replace(/<.+?>/g, function(match) { tags.push(match); return "" })
   "This is HTML#a{}This is more HTML.#b{}"
   > tags
   ["<br>", "<style>", "</style>", "<style>", "</style>"]

(An obligatory notice about regexes not being suitable for parsing markup languages).

Upvotes: 2

Related Questions