简体   繁体   English

用String.replace()替换正则表达式

[英]replace " using String.replace() with regex

I have following string 我有以下字符串

"content \" content <tag attr1=\"val1\" attr2=\"val2\">content \" content</tag> content \" content"

I want to replace all " characters inside tags definitions to ' character with use String.replace() function. " characters inside tag content must remain in its present form. 我想替换所有"内部标签定义字符'与使用的字符String.replace()函数。 "标签内容中的字符必须保持其目前的形式。

"content \" content <tag attr1='val1' attr2='val2'>content \" content</tag> content \" content"

Maybe is regex with some grouping can used? 也许正则表达式可以与某些分组一起使用?

You can use replace() and a regex-callback to do this for you: 您可以使用replace()和正则表达式回调为您执行此操作:

var str = 'content " content <tag attr1="val1" attr2="val2">content " content</tag> content " content';

function replaceCallback(match) {
    return match.replace(/"/g, "'");
}

str = str.replace(/<([^>]*)>/g, replaceCallback);

The regex will match anything in-between < and > characters in your string and pass the matches to the replaceCallback() method which will then, as desired, replace " with ' characters. 正则表达式将匹配字符串中<>字符之间的任何内容,并将匹配项传递给replaceCallback()方法,该方法将根据需要将"替换为'字符。

Edit: The replaceCallback() was using .replace('"', "'") , but this would only replace the first " . 编辑: replaceCallback()使用的是.replace('"', "'") ,但这只会替换第一个" I've updated it to use a regex-replace instead and it now works as-desired. 我已经对其进行了更新以使用正则表达式替换,并且现在可以按需运行了。

The following code (taken from the accepted answer to this question ) will also work, without a callback, but with a less easily understandable regex. 以下代码(从该问题的公认答案中获取)也可以使用,无需回调,但使用不易理解的正则表达式。

var str = 'content " content <tag attr1="val1" attr2="val2">content " content</tag> content " content';
str = str.replace(/"(?=[^<]*>)/g, "'");
var str = "content \" content <tag attr1=\"val1\" attr2=\"val2\">content \" content</tag> content \" content";

var replaced = str.replace(/\<.*?\>/g, function(match, index){ 
  return match.replace(/"/g, "'"); // `match` will be each tag , both opening and closing. 
});

You can't do it with just one regex, you must use a combination. 您不能只使用一个正则表达式,而必须使用一种组合。 This is the way to go: 这是要走的路:

  1. Match the text within the tags, this is easy. 匹配标签中的文本,这很容易。
  2. Replace the characters from the output of the previous match with the ones you want using replace, this is also easy, now that you have done the previous match. 将您以前的比赛输出中的字符替换为您要使用replace的字符,这很容易,因为您已经完成了先前的比赛。

Salute you! 向你致敬! Whatever you are. 不管你是谁。

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

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