Question

I want to replace the HTML attribute double quote with single quote. 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")' i.e the only change here is onclick="..." is replaced with onclick='...'.

In my case the content is retrieved from an HTML editor whose content needs to be cleaned in client side using 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.

I have tried something like: jsFiddle

I am looking for any solution. Any help is highly appreciated.

Thanks.

Was it helpful?

Solution

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")\''));

OTHER TIPS

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>

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

var p = s.replace(/(onclick=")(.*)(\")/,function(match,prefix,handler,suffix){
    return prefix.replace(/"/,'\'') + handler + suffix.replace(/"/,'\'');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top