简体   繁体   中英

Javascript: How to add two Stringarray - Elements to one String and without breaking lines

I want to print randomly a name with first name and surname. But between the first name and surname the lines were breaking.

The Code:

            var req1 = read("germannames.txt");
            var req2 = read("surnames.txt");
            var firstNames = req1.split(";");
            var surNames = req2.split(";");
            var randoms = "numbers:";

            var times= parseInt(document.getElementById('times').value);

         for (var i = 0; i < times; i++) {

                var firstNumber = parseInt(Math.random() * firstNames.length +1);
                var surNumber = parseInt(Math.random() * surNames.length +1);

                var name = firstNames[firstNumber] + surNames[surNumber];

                document.getElementById('result').value += name;
        }

I read the text for the array:

        function read(fileName)
        {
            var xhr = new XMLHttpRequest();

            xhr.open("GET", "http://localhost/Bowixel/" + fileName, false);

            xhr.send(null);

            return xhr.responseText;
        }

The output: 输出量

And how it should work: 结果

I don't know how to solve this problem.

You may need to remove the line feeding from the firstNames[firstNumber] , such as

var name = firstNames[firstNumber].replace(/^\n|\n$/g, '') + surNames[surNumber];

or try to use trim() if it is not a problem to remove the whitespace from both sides of a firstNames, like

var name = firstNames[firstNumber].trim()  + ' '+ surNames[surNumber];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM