1

I am inserting a json string value as a value of a button element attribute, like for example below

var $json = JSON.stringify('{"Long_text":"This is \'my json string and soon..."}');

$("#button_id").attr('data-json', $json);

This works in some of my pages but when there is a single quote in the text even if it is escape with a slash the value in the element attribute creates newline and it breaks like:

<button data-json="{"Long_text":"This is \' "

"my json string and soon..."}" >Click</button>

I have tried using

replace('/\r?\n|\r|\n/g/',''); //to replace multiple newlines

Even if I replace the double spaces it doesn't work because the attribute itself was malformed. So when I get the attribute and try to parse the json value it cause an error.

I have found this,"->Line break inside HTML tag attribute value" should I replace the spaces with this %0D%0A ? as suggested to preserved newlines or spaces?

Any help or advise is well appreciated! Thanks!

1
  • 1
    i would suggest trying the option you yourself mentioned first, it is best to try all your options because it just might work and then you wouldn't even have needed to ask the question in the first place! :) Commented Jul 13, 2018 at 13:53

1 Answer 1

1

I found a solution other than replacing the spaces with this %0D%0A from this Line break inside HTML tag attribute value

var base64 =
            {
                encode: function utoa(str)
                {
                    return window.btoa(unescape(encodeURIComponent(str)));
                },
                decode: function atou(str)
                {
                    return decodeURIComponent(escape(window.atob(str)));
                }
            }

I tried this and it works, it also make the string non-readable since it is base64_encoded, it avoid the line breaks caused by spaces and quotes.

var $json = base64.encode(JSON.stringify('{"Long_text":"This is \'my json string and soon..."}'));

$("#button_id").attr('data-json', $json);

then get the value and convert it again,

var valid_json = JSON.parse(base64.decode($("#button_id").attr('data-json')));

Thanks!

Sign up to request clarification or add additional context in comments.

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.