3

I don't understand why this outputs 'now ' when it should output 'now'.

mainQueryString = 'now ';
mainQueryString = mainQueryString.replace('/\s+$/g', ''); /* query without the ending space */
console.log('mainQueryString:', '\''+mainQueryString+'\'');

still outputs 'now ' (with whitespace in the end).

Aiden
  • 1,147
  • 2
  • 10
  • 25

5 Answers5

8

Why using regex?

Use trim method.

mainQueryString = 'now ';
mainQueryString = mainQueryString.trim();
Iswanto San
  • 18,263
  • 13
  • 58
  • 79
4

Just drop those single quotes around the regex pattern not to match the literal string but the pattern according to javascript syntax:

mainQueryString = mainQueryString.replace(/\s+$/g, '');
console.log('mainQueryString:', '\''+mainQueryString+'\'');// 'now'

It is worth mentioning that trim() method is not available in older browsers, like IE7 - more about it here: Trim string in JavaScript?

Community
  • 1
  • 1
n-dru
  • 9,285
  • 2
  • 29
  • 42
1

Someone already mentioned trim which is a better solution for this, but the reason your regex isn't working is because you wrapped it in single quotes, turning it into a regular string.

Examples:

var foo = 'foo'.replace('/foo/', 'bar'); // Will contain 'foo'
var bar = 'foo'.replace(/foo/, 'bar'); // Will contain 'bar'
George Bahij
  • 597
  • 2
  • 9
0
   //To support only internet explorer 9 and above :
   var str= "now    " ;
   console.log(str.trim()) ;

   //To support internet explorer 8 and below as well :

   if(typeof String.prototype.trim !== 'function') {
     String.prototype.trim = function() {
       return this.replace(/^\s+|\s+$/g, ''); 
     }
   }
   var str= "now    " ;
   console.log(str.trim()) ;

//Note : You may also use the trim() method from any JavaScript library like Jquery.js , or dojo.js if you are using them in your project.

Subhadeep Ray
  • 909
  • 6
  • 6
0

You dont need regex for this,since trim method is not supported in old browsers you can achieve this using plain javascript:

var mainQueryString = 'now ';
mainQueryString = mainQueryString.substring(0,mainQueryString.lastIndexOf(" "));
nehal gala
  • 131
  • 1
  • 8