neo33 neo33 - 5 months ago 9
Javascript Question

How to get an array with the following specifications?

I am writing a script to extract an array of words of my textarea which looks like this:

<textarea cols="150" rows="15" id="texto">
"RBD|X|RBD3|C|92173~GJHGWO.NAYE" "SAMBORNSiPOSSSTHRa1"
"RBD|X|RBD|C|92173~GJHGX4.NAYE" "SAMBORNSiPOSSSTHRa"
"RBD|X3|RBD3|C|92173~GJHGX6.NAYE" "SAMBORNSiPOSSSTHRa1"
"RBD|X|RBD|C|92173~GJHGX8.NAYE" "SAMBORNSiPOSSSTHRa2"
"RBD|X|RBD|C|92173~GJHGXA.NAYE" "SAMBORNSiPOSSSTHRa2"
"RBD|X3|RBD|C|92173~GJHGXC.NAYE" "SAMBORNSiPOSSSTHRa"
</textarea>


I would like to obtain an array from this one, considering as separators the following symbols: "|", "~" and " " consequently my desired output would be an array with the following structure:

["RBD", "X", "RBD3", "C", "92173", "GJHGWO.NAYE", "SAMBORNSiPOSSSTHRa1",...,"SAMBORNSiPOSSSTHRa"]


In order to achieve this, I tried:

var text = document.getElementById("texto").value;
console.log(text);
var splitWords = text.split(/[["\|~]/);
console.log(splitWords);


but I failed since I get:

["", "RBD", "X", "RBD3", "C", "92173", "GJHGWO.NAYE", " ", "SAMBORNSiPOSSSTHRa1", "↵", "RBD", "X", "RBD", "C", "92173", "GJHGX4.NAYE", " ", "SAMBORNSiPOSSSTHRa", "↵", "RBD", "X3", "RBD3", "C", "92173", "GJHGX6.NAYE", " ", "SAMBORNSiPOSSSTHRa1", "↵", "RBD", "X", "RBD", "C", "92173", "GJHGX8.NAYE", " ", "SAMBORNSiPOSSSTHRa2", "↵", "RBD", "X", "RBD", "C", "92173", "GJHGXA.NAYE", " ", "SAMBORNSiPOSSSTHRa2", "↵", "RBD", "X3", "RBD", "C", "92173", "GJHGXC.NAYE", " ", "SAMBORNSiPOSSSTHRa", "↵"]


which contains several symbols that I don't want such as: "↵", "" and
" " I would like to appreciate any suggestion to fix it.

At the past I posted a question very similar but at that time I wanted to obtain a distinct array, that structure was:

splitWords = [RBD,X,RBD,C,92173,GJHGWO.NAYE,...,SAMBORNSiPOSSSTHRa]

Answer

This might do your job well

var ta = document.getElementById("texto");
   arr = texto.value.replace(/"/g,"").replace(/\n$/g,"").replace(/~/g,"|").replace(/\s+/g,"|").split("|");
console.log(arr);
<textarea cols="150" rows="15" id="texto">
"RBD|X|RBD3|C|92173~GJHGWO.NAYE" "SAMBORNSiPOSSSTHRa1"
"RBD|X|RBD|C|92173~GJHGX4.NAYE" "SAMBORNSiPOSSSTHRa"
"RBD|X3|RBD3|C|92173~GJHGX6.NAYE" "SAMBORNSiPOSSSTHRa1"
"RBD|X|RBD|C|92173~GJHGX8.NAYE" "SAMBORNSiPOSSSTHRa2"
"RBD|X|RBD|C|92173~GJHGXA.NAYE" "SAMBORNSiPOSSSTHRa2"
"RBD|X3|RBD|C|92173~GJHGXC.NAYE" "SAMBORNSiPOSSSTHRa"
</textarea>