Concatenated white space does not display in result

匆匆过客 提交于 2019-12-10 23:02:50

问题


The padding I want is not properly concatenating, i.e. the white spaces are not showing up. Not sure why it isn't showing up and have been at it for a couple hours tweaking the code with no solution in sight.

var padWord = function(word){
    if(endsInPunctuation(word)){
        trueLength = (word.length)-1;
    }else{
        trueLength = word.length;
    }
    switch(trueLength){
        case 1:
            word = "   " + word.fontcolor("red");
            break;
        case 2:
            word = "  " + word.replaceAt(1, word.charAt(1), "red");
            break;
        case 3:
            word = "  " + word.replaceAt(1, word.charAt(1), "red");
            break;

回答1:


Browsers collapse more than one whitespace character by default. Use nonbreaking spaces &nbsp; or css white-space:pre; or the html tag <pre>




回答2:


There's nothing wrong with the string concatenation. The spaces are getting added to the string. The problem is in how you're displaying the result. In most cases, whitespace around content is collapsed in HTML elements. There are a few ways to get around this.

  1. Use CSS to override the default behavior of the HTML element by adding this line to the CSS:

    #screen{
        ...
        white-space: pre;
    }
    
  2. Convert the spaces to html entities which will be displayed. Change this:

    textShow.innerHTML = word;
    

    To this:

    textShow.innerHTML = word.replace(/\s+/, function(s) {
        return s.replace(/\s/g, '&nbsp;');
    });
    


来源:https://stackoverflow.com/questions/22368672/concatenated-white-space-does-not-display-in-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!