1

I have a lot of HTML tags that are hardcoded inside my code as strings. I want to move them into a separate module so that i can use them as variables instead.

When i am parsing the object using JSON.parse(HTMLTags) i am getting an error

Unexpected token x in JSON

I know that is because the double quotes and i know that i can escape them using backslash. but this too much to do because they are a lot of tags. is there any other way ?

  export const HTMLTags = `{
   "h1s": {
      "greating1": "<h1 id="ms1" class="ms">ABC</h1>",
      "greating2": "<h1 id="ms2" class="ms">XYZ</h1>",
               .
               .
               .
               .
               .
      "greatingx": "<h1 id="msX" class="ms">QWE</h1>"
   }
}`;
Sahil Sharma
  • 1,813
  • 1
  • 16
  • 37
Sam
  • 39
  • 4
  • export them as a string using `JSON.stringify()` and after importing them use `JSON.parse()` to get back in the form of Object. – Ace Dec 19 '19 at 09:16
  • Are all of the tags you're interested in greeting HTML strings, like in the code there? – CertainPerformance Dec 19 '19 at 09:17
  • 1
    [look here, answered already](https://stackoverflow.com/questions/15637429/how-to-escape-double-quotes-in-json) – G.Vitelli Dec 19 '19 at 09:19

1 Answers1

0

The problem resides in quotes of your attributes. The source string itself it's not valid:

const HTMLTags = `{
   "h1s": {
      "greating1": "<h1 id='ms1' class='ms'>ABC</h1>",
      "greating2": "<h1 id='ms2' class='ms'>XYZ</h1>",
      "greatingx": "<h1 id='msX' class='ms'>QWE</h1>"
   }
}`;


console.log(JSON.parse(HTMLTags));

You can also parse it by regex:

                                                
const HTMLTags = `{
   "h1s": {
      "greating1": "<h1 id="ms1" class="ms">ABC</h1>",
      "greating2": "<h1 id="ms2" class="ms">XYZ</h1>",
      "greatingx": "<h1 id="msX" class="ms">QWE</h1>"
   }
}`;

const replaced = HTMLTags.replace(/(?<==)["']?((?:.(?!["']?\\s+(?:\S+)=|[>"']))+.)["']?/g,
                str => str.replace(/"/gi, `'`)
                );

console.log(replaced);
console.log(JSON.parse(replaced));
Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43
  • 1
    I would try to replace the quotes on the fly – SteinTheRuler Dec 19 '19 at 09:25
  • As the source of data is not clear (it's fetched ? it's a local string ?) I'm not sure where it has to be fixed. If it's a string fetched from a service maybe fixing it on the service is a better idea vs escaping via regex – Mosè Raguzzini Dec 19 '19 at 09:27
  • 1
    the regex works well. this data is just kind html tags i need to use them inside my js code. it contains SVG, videos, h1 and many others. Many thanks @MosèRaguzzini – Sam Dec 19 '19 at 10:15
  • This Regex works well on Chrome but not at any other browser. due to the lookbehind (?<==), which is not supported by most of them – Sam Jan 15 '20 at 14:48