lundi 26 mars 2018

Split a string into substrings divided by a certain character

I want to divide a string into several other substrings, identifying one each time a certain character is encountered by loop. In this case i took the question mark character as separator.

I have this code:

function myFunction() {
    var str = "Hello?world?mynameis?David";
    var res="";
    while(str.length>0){
        for(var i=0; i<str.length; i++){
            if(str.charAt(i)=="?"||i==str.length-1){
                if(i==str.length-1){
                    res = str;
                }else{
                    res = str.slice(0, i);
                }
                var text = document.createElement("p");
                document.getElementById("container").appendChild(text);
                text.innerHTML = res;
                break;
            }
        }
        str.replace(res, "");
        str = str.slice(1);
    }
}
<html>
<body>

<p>Click the button to display the extracted part of the string.</p>

<div id="container"></div>

<button onclick="myFunction()">Try it</button>

</body>
</html>

I want to split my string, in this specific case

Hello?world?mynameis?David

Into 4 strings, each one ending either with the character just before the question mark, or the last character of the string, so of course they should result as

Hello

world

mynameis

David

But as you can see by running it, they don't. Looks like the for breaks at every character, even if i put the break into a condition so that it should execute the code for printing and break only when a question mark (or the last character of str) is found.

What am i missing?


A bit of explaination of how the code is supposed to work:

In my code, the for loop have to scroll the string until the first question mark. Then i save the so-found string into res variable (beginning with the first element of str and ending with the character before the question mark encountered at i). I create a new HTML element and put the res string into it, then break the for loop.

Before starting again the for to identify the second string, i remove the res substring from str, and the question mark that will subsequently be located at index = 0, then the for loop starts again.

A while loop ensures this procedure lasts until the str is empty, and so all the substrings have been identified and printed in HTML.

NOTE 1: the substrings must be printed in the HTML as separate texts.

NOTE 2: i have to create the HTML elements dynamically, since i can't know how many question marks (and so how many substrings) are there in the given string.


P.S. Since this is my first question, i hope the format is ok and the code explaination isn't too long or unnecessary. I just wanted to be extremely clear. Be patient.




Aucun commentaire:

Enregistrer un commentaire