4

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.

6
  • 1
    Is there definitely no way to modify the editor to store it correctly? Commented Apr 28, 2014 at 7:29
  • The HTML is just wrong. Change the source with any editor you prefer. Commented Apr 28, 2014 at 7:29
  • The fact that you need to use RegEx to parse HTML means you are doing it wrong. Commented Apr 28, 2014 at 7:32
  • I think you should replace your logic. Commented Apr 28, 2014 at 7:34
  • @setec I don't think this counts as parsing HTML with regex - the OP doesn't want to extract any data, just correct it syntactically. Commented Apr 28, 2014 at 7:34

2 Answers 2

1

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")\''));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. The Regex worked from me. I just modified it to: /onclick="Track\("([\s\S]+)"\)"/
0

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(/"/,'\'');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.