1

SpreadsheetApp.getUi().alert('foo bar')

When I use this piece of code, it appears as 'foo bar', removing the additional spaces in between. is there a way coerce Google App Script to do otherwise? It appears to only remove additional spaces, which makes sense, but I'd rather have spaces than dashes. If there isn't a way to do it through the UI API, what alternatives do I have?

0

2 Answers 2

4

Instead of using spaces consider using non-breaking spaces \xa0 instead.

The following code uses the String.prototype.replace with a regular expression / /g * to replace all spaces with non-breaking spaces.
* Global flag g is required or it'll only replace the 1st space.

function myFunction() {
  const message = 'foo        bar'.replace(/ /g,'\xa0');
  SpreadsheetApp.getUi().alert(message);
}

If using this repeatedly in your script, you could also create a function and call it where needed:

function myFunction() {
  const message = noBreakSpaces('foo        bar');
  SpreadsheetApp.getUi().alert(message);  
  
  function noBreakSpaces(txt) {
    return txt.replace(/ /g, '\xa0');
  }
}
1
  • Oh thanks this works! That's a nifty trick I'll keep in mind.
    – David Tan
    Commented Mar 21, 2022 at 3:14
0

I created a short function from Rubén's solution:

function SpaceBuilder(spaces){  
    var mySpaces = ' ';  
    for(var nnn=1;nnn<spaces;nnn++){  
        mySpaces = mySpaces + ' ';  
    }  
    return mySpaces.replace(/ /g,'\xa0');  
}

Example:

var xxx = SpaceBuilder(5);  
Ui.alert('Hello' + xxx + 'World')

Results:

Hello     World
1
  • 1
    OP doesn't indicate a need for reuse but even so, this seems to add new requirements unnecessarily. This seems to be an answer to a different question. See the updated accepted answer for how the functionality could be transferred to a function without changing the requirements.
    – Blindspots
    Commented Jun 13 at 20:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.