I want to add the white space in the beginning and the end of a string if there isn't.
If there is a whitespace at the beginning it will add at the end, and if there is at the end will add at the beginning
var string='This is test';
=>
var string=' This is test ';
or
var string='This is test ';
=> will only add at the beginning
var string=' This is test ';
This is simple. Check below:
let string ='This is test'; console.log(string); // No space console.log(" " + string.trim() + " "); // space at start and end
You can try this code.
var string='This is test ';
var result = " "+string.trim()+" "; //trim will remove white space before and after string
alert(result);
只需尝试删除所有可能的空格,然后在开头和结尾处手动添加一个空格即可:
string = ' ' + string.trim() + ' '
Use regex and capturing. ^\\ |\\ $|(^\\ \\ $) will match beginning space, ending space, and both: use accordingly
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.