使用JavaScript正则表达式匹配和替换字符串 [英] Match and replace a string using JavaScript regex

查看:151
本文介绍了使用JavaScript正则表达式匹配和替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑 不是重复的问题.这详细说明了使用函数而不是字符串来处理替换后的字符串的功能.

我需要提取正则表达式匹配的结果,然后将其替换为空字符串.如果使用match,则不会执行替换,如果使用replace,则不会返回匹配的内容.可以同时进行两个步骤,还是总是分两步进行?

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?

例如,我需要从HTML字符串中提取所有标签,将其保存以进行单独处理,然后将其替换为空字符串.

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

我可以立即处理span标签,或者如果它们都一起返回,则可以稍后处理.

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

推荐答案

它是这样的:

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

这篇关于使用JavaScript正则表达式匹配和替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆