简体   繁体   English

使用 JavaScript regex 匹配和替换字符串

[英]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.例如,我需要从一个 HTML 字符串中提取所有标签,单独保存以进行处理,然后将其替换为一个空字符串。

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.我可以立即处理 span 标签,或者如果它们一起返回,则稍后处理。

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). (关于正则表达式不适合解析标记语言的强制性通知)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM