سؤال

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;
هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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;');
    });
    
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top