Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create string with multiple spaces in JavaScript

By creating a variable

var a = 'something' + '        ' + 'something' 

I get this value: 'something something'.

How can I create a string with multiple spaces on it in JavaScript?

like image 280
István Avatar asked Nov 05 '15 08:11

István


People also ask

How do you add multiple spaces in JavaScript?

A common character entity used in HTML is the non-breaking space ( ). Remember that browsers will always truncate spaces in HTML pages. If you write 10 spaces in your text, the browser will remove 9 of them. To add real spaces to your text, you can use the   character entity.

How do you put a space in a string in JavaScript?

To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split(''). join(' ') . Copied!

How do I split a string into multiple spaces?

To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str. trim(). split(/\s+/) . The regular expression will split the string on one or more spaces and return an array containing the substrings.

How do I split a space in JavaScript?

To split a string keeping the whitespace, call the split() method passing it the following regular expression - /(\s+)/ . The regular expression uses a capturing group to preserve the whitespace when splitting the string.


1 Answers

In 2022 - use ES6 Template Literals for this task. If you need IE11 Support - use a transpiler.

let a = `something       something`; 

Template Literals are fast, powerful, and produce cleaner code.


If you need IE11 support and you don't have transpiler, stay strong 💪 and use \xa0 - it is a NO-BREAK SPACE char.

Reference from UTF-8 encoding table and Unicode characters, you can write as below:

var a = 'something' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0' + 'something'; 
like image 157
Andrew Evt Avatar answered Sep 21 '22 15:09

Andrew Evt