Framework: React
So when I'm running the code below I console.log the objects.
When looking at the first object is pushed to the array then it contains text but when looking at the array of objects afterward it's empty.
The index 5 that is marked should be the object being pushed in the array in the red rectangle.
How come?
The code
const SplitHtml = () => {
const string =
'<p><strong>Add and edit text here. <a target="_blank" rel="noopener noreferrer" href="https://www.google.com">This is a link</a> Select text to format it.</strong></p><p> </p><p></p>'
const stringArray = string.split(/(<[^>]+>)/)
let textArray = []
let object = {}
for (let i = 0; i < string.length; i++) {
console.log(i, object.text)
if (stringArray[i] === undefined) break
// Print out
if (stringArray[i].startsWith("<") && object.text && object.text.length > 0) {
console.log(i, " push")
textArray = [...textArray, object]
}
// Elements
else if (stringArray[i] === "<p>") {
object.type = "text"
} else if (stringArray[i] === "<h1>") {
object.type = "headline"
object.importance = "1"
} else if (stringArray[i] === "<h2>") {
object.type = "headline"
object.importance = "2"
} else if (stringArray[i] === "<h3>") {
object.type = "headline"
object.importance = "3"
} else if (stringArray[i] === "<h4>") {
object.type = "headline"
object.importance = "4"
} else if (stringArray[i] === "<h5>") {
object.type = "headline"
object.importance = "5"
} else if (stringArray[i] === "<h6>") {
object.type = "headline"
object.importance = "6"
} else if (stringArray[i].startsWith("<a")) {
object.type = "link"
}
// Style
else if (stringArray[i] === "<strong>") {
object.bold = true
} else if (stringArray[i] === "</strong>") {
object.bold = false
} else if (stringArray[i] === "<i>") {
object.italic = true
} else if (stringArray[i] === "</i>") {
object.italic = false
}
// Text
else if (!stringArray[i].startsWith("<")) {
object.text = stringArray[i]
}
}
console.log(textArray)
}
The screenshot
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…