Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove more than one space between two words of string in angular?

this.folderObj.folderName is string and I print console of that string aaa aaa, I use trim() but it removes only before and after white spaces,how to remove more than one space between two words of string and want output like this aaa aaa

  folderObj : Folder = new Folder();

  console.log(this.folderObj.folderName.trim());  // aaa         aaa

expected console that i want

console.log(this.folderObj.folderName.trim())  // aaa aaa
like image 792
Dharmesh Avatar asked Dec 03 '18 08:12

Dharmesh


3 Answers

Use a regular expression to match two or more space characters, and replace with a single space:

const folderName = '    aaa         aaa';
console.log(
  folderName
    .replace(/ {2,}/g, ' ')
    .trim()
);

Of course, you could also match one or more space characters instead with +, the code will look nicer, but it'll be very slightly less efficient:

const folderName = '    aaa         aaa';
console.log(
  folderName
    .replace(/ +/g, ' ')
    .trim()
);
like image 63
CertainPerformance Avatar answered Oct 02 '22 08:10

CertainPerformance


Try with replace() to replace all single and multiple spaces with single space.

this.folderObj.folderName.trim().replace(/ +/g, ' ');

Demo:

console.log('aaa         aaa'.replace(/ +/, ' '))
like image 35
Mamun Avatar answered Oct 02 '22 07:10

Mamun


let folderName = '      abcd       xya   ';
console.log(folderName.replace(/\s+/g, ' ').trim());
like image 23
Rohit.007 Avatar answered Oct 02 '22 07:10

Rohit.007