Ashish Kamble
Ashish Kamble

Reputation: 2627

convert draftjs styled string into html code text string

I have string of data look like json but its string this

{
"blocks":[
{"key":"3uff",
"text":"TextInBold TextInUnderLined TextInItalic",
"type":"unstyled",
"depth":0,
"inlineStyleRanges":[
{"offset":0,"length":11,"style":"BOLD"},
{"offset":11,"length":28,"style":"UNDERLINE"},
{"offset":28,"length":41,"style":"ITALIC"}],
"entityRanges":[],
"data":{}
}
],"entityMap":{}
}

what to do is take TextInBold and make it according to

`<bold>TextInBold</bold>`
`<u>TextInUnderLined</u>`
`<i>TextInItalic</i>`

by looking at

`{"offset":0,"length":11,"style":"BOLD"},`

similarly TextInUnderLined should be like <u>TextInUnderLined</u> as it has offset 28 length until 41

Upvotes: 0

Views: 129

Answers (1)

malarres
malarres

Reputation: 2946

You need to play with the keys and values in the object. For example, what you ask:

data = {
"blocks":[
{"key":"3uff",
"text":"TextInBold TextInUnderLined TextInItalic",
"type":"unstyled",
"depth":0,
"inlineStyleRanges":[
{"offset":0,"length":11,"style":"BOLD"},
{"offset":11,"length":28,"style":"UNDERLINE"},
{"offset":28,"length":41,"style":"ITALIC"}],
"entityRanges":[],
"data":{}
}
],"entityMap":{}
}


console.log(`<${data.blocks[0].inlineStyleRanges[0].style}>${data.blocks[0].text.substring(data.blocks[0].inlineStyleRanges[0].offset,data.blocks[0].inlineStyleRanges[0].length)}</${data.blocks[0].inlineStyleRanges[0].style}>`)

notice that it can get complex quickly, e.g.: Can you have portions that are bold and underlined at the same time?

Upvotes: 1

Related Questions