最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin7PV0评论

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

Post a comment

comment list (0)

  1. No comments so far