Transforming the HTML code into BBCode for Mobile Legends conversion

Currently, I am developing an innovative in-game text app for the popular game Mobile Legends. This app allows users to customize the color of their chat texts during gameplay. In addition to changing colors, users can also apply other styling options such as bold, italic, underline, and strike-through, resulting in a code that can be directly inputted into the game. The app is designed with user-friendliness and speed in mind, but I am facing some challenges when it comes to the creative aspects.

The website:

I have developed my own rich editor utilizing the execcommand feature. However, I need a solution that can convert the HTML format generated by the rich editor into the text format compatible with Mobile Legends.

The Text Format in Mobile Legends

The formatting in Mobile Legends mirrors that of HTML. For instance, instead of using <b>Hello World</b>, it utilizes brackets like [b]Hello World[/b].

These are some common text formats in Mobile Legends which closely resemble HTML:

Bold: [b]Hello World[/b]

Italic: [i]Hello World[/i]

Underline: [u]Hello World[/u]

StrikeThrough: [s]Hello World[/s]

ForeColor: [FF0000]Hello World (uses hex code)

The Issue at Hand

The challenge is how to convert this code (example output):

Hello World!

<b><i><u><strike>Hello World!</strike></u></i></b>

into this format:

[b][i][u][s]Hello World![/b][/i][/s]

Proposed Solution

I have attempted to use the method of .replace(/<b>/g,'[b]'). However, as the formatting becomes more complex, replacing the tags becomes increasingly difficult. This leads to complicated code with numerous attributes.

Example of a complex format:

Lorem ipsum dolor sit amet.

<span style="font-family: &quot;Open Sans&quot;, Arial, sans-serif; font-size: 14px; text-align: justify; background-color: rgb(255, 255, 255);"><span style="text-decoration: underline;"><font color="#a9fcd4"><i>Lo</i><b>rem</b></font></span> <i style="text-decoration: underline;"><font color="#0000cc">ipsu<b>m</b></font></i> <b style="text-decoration: underline;"><i><font color="#cc00cc">dolor</font></i></b> <u><font color="#cccc00">sit</font></u> <strike><font color="#cc00cc"><b>amet</b><i>.</i></font></strike></span><br>

Disclaimer: I do not claim to be a professional coder, so I apologize for any novice errors in my work. Coding is simply a hobby of mine, and I decided to create this app for the Mobile Legends community since I enjoy playing the game and wanted to enhance my bio and chat text.

Answer №1

To effectively analyze the input, utilize a DOM parser to parse it first. Then proceed to navigate through the DOM structure recursively while examining the style attributes of each node to determine the necessary tags and colors. Here's an outline of how this process could be implemented:

function parseHTML(htmlContent) {
    let selectedColor = "000000";
    
    function parseNode(styleProperties, colorInherited, currentNode) {
        // Base case: handle plain text nodes:
        if (currentNode.nodeType === 3) {
            if (colorInherited !== selectedColor && currentNode.nodeValue.trim()) {
                selectedColor = colorInherited;
                return `[${selectedColor}]${currentNode.nodeValue}`;
            }
            return currentNode.nodeValue;
        }
        // Transfer color attribute from FONT to style attribute:
        if (currentNode.nodeName === "FONT" && currentNode.color) currentNode.style.color = currentNode.color;

        // Extract relevant styles for the current node
        let {color, textDecorationLine, fontWeight, fontStyle} = currentNode.style;
        color = color || colorInherited;

        // Determine U,S,B,I properties:
        let styles = {
            u: styleProperties.u || currentNode.nodeName === "U" || textDecorationLine.includes("underline"),
            s: styleProperties.s || currentNode.nodeName === "STRIKE" || textDecorationLine.includes("through"),
            b: styleProperties.b || currentNode.nodeName === "B" || fontWeight.includes("bold") || +fontWeight >= 700,
            i: styleProperties.i || currentNode.nodeName === "I" || fontStyle.includes("italic")
        };
        
        // Handle color conversion
        if (color.slice(0,4) === "rgb(") {
            color = color.match(/\d+/g).map(dec => (+dec).toString(16).padStart(2, "0")).join("").toUpperCase();
        }

        // Recursively apply parsing to child nodes
        let result = Array.from(currentNode.childNodes, parseNode.bind(null, styles, color)).join("");

        // Wrap the content within appropriate [] tags
        for (let prop in styles) {
            if (styles[prop] !== !!styleProperties[prop]) {
                result = `[${prop}]${result}[/${prop}]`;
            }
        }
        return result;
    }
    
    return parseNode({}, "000000", new DOMParser().parseFromString(htmlContent, "text/html").body);
}

// Example Usage
let htmlInput = `<span style="font-family: "Open Sans", Arial, sans-serif; font-size: 14px; text-align: justify; background-color: rgb(255, 255, 255);"><span style="text-decoration: underline;"><font color="#a9fcd4"><i>Lo</i><b>rem</b></font></span> <i style="text-decoration: underline;"><font color="#0000cc">ipsu<b>m</b></font></i> <b style="text-decoration: underline;"><i><font color="#cc00cc">dolor</font></i></b> <u><font color="#cccc00">sit</font></u> <strike><font color="#cc00cc"><b>amet</b><i>.</i></font></strike><</span><br>`;

console.log(parseHTML(htmlInput));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display the cost based on the selection made

I am currently working on a restaurant website and have designed a form with select options. My goal is to have a price appear for the selected option. While I know that JavaScript is the solution for this, I must admit that I am not very proficient in Jav ...

Which file does require('./bar') try to load first - 'bar' or 'bar.js'?

Referencing the material found at , I came across an intriguing passage: The require function in Node.js allows us to import JSON files and C++ addon files without explicitly stating their file extensions. When no extension is provided, Node will first l ...

Is there a way to separate elements with a comma explode function in PHP?

My situation involves working with a JavaScript array that I encode using JSON.stringify() and then append to the URL. Upon decoding it in PHP using $_GET, I am left with a string formatted like this: ["a","\nb","\nc","\nd"] Now, my task i ...

Learn how to troubleshoot and resolve a bug in the mobile Chrome browser that pertains to the position fixed feature

On the mobile version of Firefox, everything works perfectly. However, there seems to be a bug in Chrome with the fixed positioning. When scrolling, the header should change from absolute to fixed and the height should go from 65 to 35 pixels. Unfortunatel ...

Adding a MySQL-PHP combination programmatically

Currently, I am working on a custom HTML page that sends data to PHP variables which are then utilized to generate customized SQL queries. function load_table($db, $old_table, $startRow, $nameColumn, $ipColumn, $addressColumn, $cityColumn, $stateColumn, $ ...

Click on link after animation has finished

I'm currently facing an issue with my script not functioning correctly. The code I'm utilizing is from a resource provided by Codyhouse to implement a 3D rotating navigation menu on my webpage. Essentially, when you click the hamburger icon, it o ...

Type-safe Immutable.js Records with TypeScript

I'm struggling to find a suitable solution for my query. I am aiming to define data types using an interface in TypeScript, but my data consists of Immutable.js records making it more complex. Please refer to the example provided below. interface tre ...

What is the best way to loop through an array of strings and make them all plural?

I am currently working on a challenge where the objective is to take an array and pluralize each element by adding an 's' at the end of it. Here's my attempt so far, but I suspect that there might be mistakes in my code: var pets = [' ...

Guide for executing Java code and displaying HTML form fields concurrently in JSP

I have created a JSP page with form fields and Java code in scriptlets. I have imported the Java code into the JSP page and created an object to call the functions of that Java class. When I run the JSP, the page remains blank until all the Java code has ...

Perform an action in jQuery when a class is modified

I am trying to create an event that will trigger when a specific element receives a class, and also when that class is removed. For example: <button id="my_butt_show">showtime</button> <button id="my_butt_hide">hide me</button> &l ...

Error: An unexpected character was found in the Gulpfile.js

Having an issue in my Gulpfile.js: gulp.task('webpack', gulp.series(async () => { const option = yargs.argv.release ? "-p" : "-d"; execSync(`node_modules/webpack-cli/bin/cli.js ${option}`, { stdio: [null, process.stdout, proce ...

Guide to adding up the radio button values with Javascript

The tutorials I have reviewed include: How might I calculate the sum of radio button values using jQuery? How to find a total sum of radio button values using jQuery/JavaScript? How might I calculate the sum of radio button values using jQuery? Unfortu ...

Is it possible to define the sequence of wrapped items in CSS flexbox?

I am using a <div> with CSS flex to maintain responsiveness. I want to control the order in which elements are wrapped. For instance, I need 1 - 2 - 3 To be rearranged as 1 3 2 Once fully wrapped. Here is my current code: https://jsfiddle.net/ ...

Struggling to assign the value of a JavaScript variable to an HTML field?

Is it possible to click on an HTML cell and extract the cell's html data, then insert it into a form field for future use? I have been able to assign a value directly through coding like: blah = 99; however, when trying to change that value to a varia ...

What is the best way to pass the value from one JavaScript file to another in the ViewModels and main JavaScript file?

https://i.sstatic.net/pzFAS.jpg Within the login.js file, a REST API is returning specific values that need to be utilized in the Dashboard.html file. However, the values are not being retrieved successfully in the dashboard.js file. A similar requiremen ...

Possible revision: "Trouble with event triggering when using an anchor tag within an <li> element

I am currently working with a horizontal menu plugin where I am including anchor tags within the <li> elements to create menu items. I have set up an onmouseover event for the anchor tag to display the submenu when the mouse hovers over it. However ...

In what ways can a distant ancestor influence its subsequent generations down the line?

As a beginner utilizing Bootstrap v5, I am in the process of creating a navbar using the following HTML code. Within this code, the parent element (ul) of my link items contains a class called "navbar-nav" which results in my link items being styled to s ...

When sending a nested data object using Node Axios POST, a 500 error is encountered, but using a flat object works flaw

For my expressjs app, I am implementing a straightforward POST request using axios as shown below: const try = async () => { const axios = require('axios'); const output = { url: "www.example.com"} await axios.post(`http://lo ...

Multiple popups being displayed repeatedly in tablet application

I am currently working on creating a table and assigning a function to the onTap attribute. The issue I'm facing is that when there are 3 table rows, the prompt opens 3 times. Does anyone have any suggestions on how I can resolve this? if(window.lo ...

How can I resolve the error "Unable to use 'K extends X[T] ? keyof K : never' to access type for nested objects"?

I am currently working on developing a function with specific parameters. The first parameter, 'data', should be an array consisting of objects of type Product. The second parameter, 'element', can be any property within Product. Additi ...