Reputation: 1211
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?
Upvotes: 0
Views: 98
Reputation: 457
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:
Upvotes: 1