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 ';
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 ';
Share
Improve this question
asked May 7, 2018 at 5:55
EyTaEyTa
1093 silver badges10 bronze badges
2
- 1 what does you prevent to do so? – Nina Scholz Commented May 7, 2018 at 5:56
- 3 what have you tied so far ? – Muhammad Usman Commented May 7, 2018 at 5:56
4 Answers
Reset to default 2You can try this code.
var string='This is test ';
var result = " "+string.trim()+" "; //trim will remove white space before and after string
alert(result);
Just try with removing any possible whitespaces and add one on the beginning and end manually:
string = ' ' + string.trim() + ' '
This is simple. Check below:
let string ='This is test';
console.log(string); // No space
console.log(" " + string.trim() + " "); // space at start and end
Use regex and capturing. ^\ |\ $|(^\ \ $) will match beginning space, ending space, and both: use accordingly
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745656166a4638555.html
评论列表(0条)