1

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.

4
  • 1
    .replace takes a callback, you can extract the data in there, and return the replacement. Commented Jan 13, 2014 at 22:23
  • I'm not clear on what you're asking. What problem are you trying to solve? Commented Jan 13, 2014 at 22:25
  • Is the string you're running the regex on well formed html? If so then you may want to use xpath for this. If the string is part of your current document object then you DEFINITELY want to use xpath for this. Commented Jan 13, 2014 at 22:53
  • Thanks to everyone. This is not a duplicate question because the other post, which I had already read, did not explain the ability to use a function as the second parameter. Commented Jan 14, 2014 at 14:29

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.