I have a long string with Headers and Sub-headers. Every header is supposed to have a sub header, but the string pre-processing, does not. I need to manipulate it in such a way that every header has a Sub-header.
Every header that does not have a string has a reference point under different header. The header missing the subheader needs to grab the subheader from the reference’s immediate parent/proceeding header.
Here’s what it looks like:
Header 1
subheader - somedata A
text
reference-header-3
stuff in the way
Header 2
subheader - somedata B
stuff in the way
stuff in the way
Header 3
stuff in the way
stuff in the way
reference-header-5
Header 4
subheader - somedata C
some text
Header 5
more text
I need to get it to be like this:
Header 1
subheader - somedata A
text
reference-header-3
stuff in the way
Header 2
subheader - somedata B
stuff in the way
stuff in the way
Header 3
subheader - somedata A [this is copied from header 1]
stuff in the way
stuff in the way
reference-header-5
Header 4
subheader - somedata C
some text
Header 5
subheader - somedata A [this is copied from header 3]
more text
If anyone know of any string libraries that can help do this that would be awesome. I don’t know how to go about this, I’m thinking of converting them to DOM elements so I can traverse them with jQuery, and then convert back. But that sounds a little icky.
Anyone know how to do this?
Thanks in advance.
If you have control over the backend, you should have this data sent over as JSON. That would be the best bet. It is also relatively painless. You also shouldn’t be using jQuery for this (its use is rather irrelevant here) unless you were using AJAX to fetch JSON like I described.
Or you can do something like this:
Now you have a map that is keyed by
Header 1andHeader 2and so on. The value for each key is an array that contains the various subheaders. You can easily iterate over these values and check the very first value in the array to see if it has thesubheader -prefix. If not, you can add it.I just noticed the second part. I guess what you can do after you do the above is make a second pass and parse out the
referenceparts and insert the appropriate values there. Slak’s solution might be a one-pass one I think (from the quick read I gave it). OR you can add anelse-ifto the above code (within the loop where it checks for the hedaer) to check and see if it matches yourreferencedirective. If it does, grab the existing reference and add it what you have (this only works for backward references). If you have forward references then you will need to have a second pass.