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?
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.
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!
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.
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.
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With