-1

I have a sentence like below,

var text  = 'My       name         is           Ran';

I wnat this text to print like below,

'My       name is              Ran';

I want to remove the space before 'is'.Can anyone please suggest help.Thanks.

TNTR
  • 3
  • 2
  • 3
    Possible duplicate of [How to remove double white space character using regexp?](https://stackoverflow.com/questions/3609080/how-to-remove-double-white-space-character-using-regexp) – hurricane Nov 16 '17 at 11:28
  • 5
    Possible duplicate of [Replace multiple whitespaces with single whitespace in JavaScript string](https://stackoverflow.com/questions/6163169/replace-multiple-whitespaces-with-single-whitespace-in-javascript-string) – Roberto Pegoraro Nov 16 '17 at 11:29
  • Take a look at this: https://stackoverflow.com/questions/1981349/regex-to-replace-multiple-spaces-with-a-single-space – Fabio_MO Nov 16 '17 at 11:35
  • Possible Duplicate of https://stackoverflow.com/questions/7635952/javascript-how-to-remove-all-extra-spacing-between-words – Messaoud Zahi Nov 16 '17 at 11:36

3 Answers3

1

You can use the replace method with second parameter one space.

var text  = 'My name      is  Ran';
var newString = text.replace(/\s+/g,' ');
console.log(newString);

Hope this will help you.

Olian04
  • 6,480
  • 2
  • 27
  • 54
Er. Mukesh Sharma
  • 285
  • 1
  • 4
  • 16
0

Updated for: Hi Ramesh ,how can I replace only the space before 'is', if my string is My name is Ran;

var  data='My name         is           Ran';
var  result = data.split("is");
console.log(result[0].replace(/ +/g, ' ') +"is" + result[1]);

For the OP Update 2

var  data= 'My       name         is           Ran';//
var  result = data.split("is");
var  result1 = data.split("name");
console.log( result1[0]+  "name " + "is" + result[1]);

Final Solution by the OP question update 5th

   var  data= "My       name     is           Ran";// or My       name  is           Ran

   if(data.indexOf("name   ") == -1)
   {
      var  result = data.split("is");
      var  result1 = data.split("name");
      console.log(result1[0]+  "name " + "is" + result[1]);
   } else   {
      var  result = data.split("is");
      var  result1 = data.split("name");
      console.log(result1[0]+  "name " + "is" + result[1]);
   }
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
0
text = text.replace(/\s+/g,' ').trim();