简体   繁体   中英

Javascript inserting weird newLine character

I have an array named verses that contains strings created from an ajax response. The array is created like this:

verses.push(splitStr[i].replace('\n',''));

Later I create some <span> elements and append the values from the array. However the last element from array always has a strange behavior because it contains a hidden new line character in ASCII it has the code 10 (checked that in the console). Now when I print in the console log the last element from the array a get this result: "string" . Then I create the span element that contains this string and later when I retrieve back the value from span I get:

"string
"

That's because when creating the span it always inserts this strange new line character. So in the source code the span looks like:

<span class="answer" onclick="checkAnswer(this)">potopului
</span>

You can see that the closing tag is on the next line.

In the console I used some break points and I got this value extracted from span: "string↵"

Now, has anyone any idea why when creating this span javascript inserts a new line character and why does it happen only with the last element from array?

The code used to create the span elements:

for (var i = 0; i < 3; i++) {
        if (i!=phtml) {
            tags.push("<span class='answer' onclick='checkAnswer(this)'>"+generateRandom(pos)+'</span>'); 
            //generate a  string from the array different from the one with position pos
        }else{
            tags.push("<span class='answer'  onclick='checkAnswer(this)'>"+verses[pos].replace('\n','')+'</span>');
        }
    }
    var output='';
    for (var i = 0; i < tags.length; i++) {
        output = output + tags[i];
    }
    document.getElementsByClassName('v-options')[0].innerHTML = output;

The checkAnswer() function:

function checkAnswer(e){
    var text = e.innerHTML;
    var input = document.getElementsByClassName('hidden-word')[pos];
    if (text == verses[pos]) {
        input.value = verses[pos];
        input.setAttribute('disabled','');
    }
    console.log(":"+text.substring(0, text.length-1) + ":"+verses[pos]+":");
}

Sometimes line breaks are printed in different styles. Commonly it is a combination of two special characters \\n and \\r so you just need to check all possible types of newline combinations or their lost broken parts. Try to change your RegExp to match them all :

splitStr[i].replace(/\n\r|\n|\r/g, '')

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