简体   繁体   English

用JavaScript中的正则表达式替换HTML属性值

[英]Replace HTML attribute value with regular expression in JavaScript

I want to replace the HTML attribute double quote with single quote. 我想用单引号替换HTML属性双引号。 For example: 例如:

If the input is: 如果输入是:

<a onclick="Track("http://www.example.com")">Track Me</a>

The output will be: 输出将是:

<a onclick='Track("http://www.example.com")'>Track Me</a>

Here the onclick="Track("http://www.example.com")" needs to be replaced with onclick='Track("http://www.example.com")' ie the only change here is onclick="..." is replaced with onclick='...' . 这里的onclick="Track("http://www.example.com")"需要替换为onclick='Track("http://www.example.com")'即这里唯一的变化是onclick="..."替换为onclick='...'

In my case the content is retrieved from an HTML editor whose content needs to be cleaned in client side using JavaScript. 在我的例子中,内容是从HTML编辑器中检索的,其内容需要使用JavaScript在客户端进行清理。 The only way I can currently think of is I need to use Regex to replace the onclick double quote attribute with single quote attribute and it should only happen when "Track" function is used in onclick attribute. 我目前唯一能想到的方法是我需要使用Regexonclick双引号属性替换为单引号属性,并且只有在onclick属性中使用“Track”函数时才会发生。

I have tried something like: jsFiddle 我尝试过类似的东西: jsFiddle

I am looking for any solution. 我正在寻找任何解决方案。 Any help is highly appreciated. 任何帮助都非常感谢。

Thanks. 谢谢。

If you cann't change others,then change yourself. 如果你不能改变他人,那就改变自己吧。 so here we go: 所以我们走了:

var str = '<a onclick="Track("http://www.example.com")">Track Me</a>';

console.log(str.replace(/onclick="Track\("([^"]+)"\)"/, 'onclick=\'Track("$1")\''));

If You are still looking for regular expression, You can use this example. 如果您仍在寻找正则表达式,可以使用此示例。 It will give You that link <a onclick="Track('http://www.example.com')">Track Me</a> 它将为您提供<a onclick="Track('http://www.example.com')">Track Me</a>链接

var s = '<a href="#" target="_blank" 
         onclick="Track("http://www.example.com/")">Test Link</a>';

var p = s.replace(/(onclick=")(.*)(\")/,function(match,prefix,handler,suffix){
    return prefix + handler.replace(/"/g,'\'') + suffix;
});

console.log(p);

And fiddle for demo; 并演示小提琴 ;

I did not see, that You look for version <a onclick='Track("http://www.example.com")'>Track Me</a> , so you can change above code with this line 我没有看到,您正在寻找版本<a onclick='Track("http://www.example.com")'>Track Me</a> ,因此您可以使用此行更改上述代码

var p = s.replace(/(onclick=")(.*)(\")/,function(match,prefix,handler,suffix){
    return prefix.replace(/"/,'\'') + handler + suffix.replace(/"/,'\'');
});

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

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