-3
var name="james            mark";
var name="james           " ;

so how to trim both the names occur any condition from this anytime in javascript

Output:

james mark

james

Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170

2 Answers2

2

You can replace all instances of repeated white space with a single space and also trim all leading and trailing white space:

name.replace(/\s+/g,' ');
name.replace(/^\s+|\s+$/g,''); // or use .trim()

for more information you should read the description on the .replace() and .trim() functions on MDN

Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
  • I would keep it simple by using .trim (as I see an edit suggests as I'm writing this) and also note that you can do these inline: .replace(/\s+/g, ' ').trim() – Daniel Mar 29 '18 at 18:38
  • Thxxiee can you tell me for second one in that case we don't require space so solution is name.replace(/^\s+|\s+$/g,''); this one – BhAnuJ RalHan Mar 29 '18 at 18:39
0

Try with:

var name="james            mark";
var j = names.split(' ');
alert(j[0]);

//The otput: James (without the blank spaces)
Benjamin RD
  • 11,516
  • 14
  • 87
  • 157