javascript - Add white space in the beginning and the end of a string - Stack Overflow

I want to add the white space in the beginning and the end of a string if there isn't.If there is

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
Add a ment  | 

4 Answers 4

Reset to default 2

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);

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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信