popo63301 popo63301 - 3 months ago 10
HTML Question

concatenate words of a string by comparing with words of an array in javascript

HTML:

<!DOCTYPE html>
<html>

<head>
<title>Glue words</title>
</head>

<body>
<textarea rows="20" cols="50" id="textbase">
Write text to fix after. je suis gen til l ol
</textarea>
<br>
<button type="button" onclick="gluefct()">Tokenize</button>
</body>

</html>


JS:

function gluefct() {

var space = " ";
var glueArray = ["jesuis", "gentil", "lol"];
var stringBase = document.getElementById("textbase").value;
var newString = "";

for (gluewords in glueArray) {
var arrayofstring = stringBase.split(" ");
var numberelement = arrayofstring.length;
var i = 0;

while (i < numberelement) {
var motactuel = arrayofstring[i];
var n = i;

while (motactuel.length < gluewords.length) {
n = n+1;
motactuel = motactuel + arrayofstring[n];
}

if (motactuel == gluewords) {
newString = newString + motactuel + space;
i = n+1;
}

else {
newString = newString + arrayofstring[i] + space;
i = i + 1;
}
}

stringBase = newString;
newString = "";
}

document.getElementById("textbase").value = stringBase;
}


Basically, what I'm trying to do is to stick words from a string who had been separated by checking with the complete words from an array of strings.

For example:

Here is my array:

var glueArray = ["jesuis", "gentil", "lol"];


And here is my string:

"je suis gen til lo l et voilà"


This should be the result of the function:

"jesuis gentil lol et voilà"


I don't see what's wrong with my code. Can anyone help?

BSD BSD
Answer

I'm not sure if how you are doing it is best, but your code only has a small problem. You are using a hash for glueArray which means that you are assigning key values of 0 to "jesuis" and 1 to "gentil", etc. When you use the for loop to go through the array you are getting the index values and NOT the words. I suggest this small fix which seems to work.

//your code before
for (glueIndice in glueArray) {
    var gluewords = glueArray[glueIndice];
    var arrayofstring = stringBase.split(" ");
//your code after
Comments