简体   繁体   中英

Converting custom text style code to html

I have example string which uses custom style codes for text, the combinations are always in 2 words first word is either N or B (Normal, Bold) and second word is L or R or C (Left, Right, Center). So combinations are in this format NL, BL etc...

Now i want to use CKEditor and display this with HTML codes as CKEditor requires them. What would you suggest how to tackle this? I tried with splitting string based on characters like this:

var fields = contentFromDB.split(/(NL|BL|NR|BR|NC|BC)/g);

and than in for loop tackle the string with ifs:

if(fields[i] = ("NL")) {
} else if(fields[i] = ("BL")) {
    convertedString += "<b>"
} else if(fields[i] = ("NR")) {
} else if(fields[i] = ("BR")) {
}

But the thing is i should close tag before the other one starts. So any tips how would you guys do this thing?

You should parse the identifier letter by letter by using 2 switch statement as to reduce the code and flip the order of parsing to be able to close the tag accordingly

 var contentFromDB = ""; contentFromDB += "NLLorem ipsum dolor sit amet"; contentFromDB += "BLLorem ipsum dolor sit amet"; contentFromDB += "NCLorem ipsum dolor sit amet"; contentFromDB += "BCLorem ipsum dolor sit amet"; contentFromDB += "NRLorem ipsum dolor sit amet"; contentFromDB += "BRLorem ipsum dolor sit amet"; var fields = contentFromDB.split(/(NL|BL|NR|BR|NC|BC)/g); var convertedString = ""; for(let i = 0; i<fields.length; i++){ let currentIdentifier = fields[i]; if(currentIdentifier.trim() == "") continue; switch(currentIdentifier[1]){ case "L": convertedString += "<p>"; break; case "C": convertedString += "<p align='center'>"; break; case "R": convertedString += "<p align='right'>"; } // Increase the loop walker to be able to get // The text and close the tag accordingly i++; switch(currentIdentifier[0]){ case "N": convertedString += fields[i] + "</p>"; break; case "B": convertedString += "<b>" + fields[i] + "</b></p>"; break; } } document.write(convertedString); 
 Result of parsing: 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM