Text separated by; in a list with id

2

Hello, I put this content in a list with your id

<div class="elemento">
Mascota: Perro;
País: Venezuela;
Explorador: Chrome;
Lenguaje: Español; 
</div>
<div class="elemento lista">
<ul>
<li id="Mascota"><span>Mascota:</span> <span>Perro</span></li>
<li id="País"><span>País:</span> <span>Venezuela</span></li>
<li id="Explorador"><span>Explorador:</span> <span>Chrome</span></li>
<li id="Lenguaje"><span>Lenguaje:</span> <span>Español</span></li>
</ul>
</div>

Any ideas on how to do it?

    
asked by Rolando Huaihua Merma 15.08.2016 в 06:35
source

1 answer

1

Although I do not understand how the text is generated and, understanding, I would surely recommend replacing it at the server level, this is an alternative that achieves what you are looking for. It offers a minimum validation, but it will depend on the users entering the text following the exact format.

Code

// Obtener todos los divs
var divs = document.getElementsByClassName('elemento');

// Valores a reemplazar
var regex = /^\s*([^:;\n<>]+?)\s*:\s*([^;\n<>]+?)\s*;\s*$/gm; 
var rempl = '<li id="$1"><span>$1:</span> <span>$2</span></li>'; 

// Iterar todos los divs cambiando el valor
for (var i = 0; i < divs.length; i++) {
    divs[i].innerHTML = '<ul>' + divs[i].innerHTML.replace(regex, rempl) + '</ul>';
}
<div class="elemento">
Mascota: Perro;
País: Venezuela;
Explorador: Chrome;
Lenguaje: Español; 
</div>

Description

We use the regular expression /^\s*([^:;\n<>]+?)\s*:\s*([^;\n<>]+?)\s*;\s*$/gm for:

  • ^\s* match the start of the text, followed by any number of spaces
  • ([^:\n<>]+?) followed by characters other than : , ; , < , > or line breaks (the key)
  • \s*:\s* then : optionally with spaces around
  • ([^;\n<>]+?) and characters other than ; , < , > or line breaks (the value)
  • \s*;\s* terminated with ; optionally with spaces around
  • $ and the end of the line.

To replace it with

<li id="$1"><span>$1:</span> <span>$2</span></li>

Where $1 is the key and $2 is the value.

    
answered by 15.08.2016 / 08:18
source