6

Possible Duplicate:
How do I trim a string in javascript?

By using replace method in javascript I am trying to remove the empty space between the start and the end of a string:

Here my code:

Any idea how should I achive the result?

input  -> "   first second     ".replace(/[^\s|\s$]/g, ''); // " "
output -> "first second"
Cœur
  • 37,241
  • 25
  • 195
  • 267

6 Answers6

4

This is called trimming.

You need parentheses instead of brackets in the regular expression, and also a multiplier on the white space specifier to match multiple spaces:

var s = "   first second     ".replace(/(^\s+|\s+$)/g, '');

Demo: http://jsfiddle.net/Guffa/N7xxt/

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
3

Add this at the begining of your script:

// Add ECMA262-5 string trim if not supported natively
//
if (!('trim' in String.prototype)) {
    String.prototype.trim= function() {
        return this.replace(/^\s+/, '').replace(/\s+$/, '');
    };
}

Then use yourString.trim() to remove spaces at the beginning and at the end of your string.

Alejandro Rizzo
  • 837
  • 2
  • 8
  • 14
1

You should use parentheses () to specify that you want to match either the left or right side of the pipe "|" symbol, rather than square brackets. Square brackets actually match character sets (i.e., [grapes] would match a single instance of either "g", "r", "a", "p", "e", or "s", while (grapes|apples) would match either "grapes" or "apples").

Also, another thing you're missing is an indication of "quantity". In other words, once you match a space (\s), how many spaces should it look for? In your example, it's only matching a single space character. You probably want to match as many consecutive spaces as exist on the left and right of the string. For that, you need to append * (match zero or more) or + (match one or more) immediately after the character \s.

So, to rewrite your regex:

var input = "      first second      ";
var trimmed = input.replace(/(^\s+|\s+$)/g, '');
console.log(trimmed);

You can copy and paste those lines into your JavaScript console to see that you get the desired output. The regex here literally says, "match either one or more space characters from the start of the string, or one or more space characters immediately followed by the end of a string." Then the replace function takes that match and replaces it with ''.

JoeLinux
  • 4,198
  • 1
  • 29
  • 31
0

Why replace method? Just use trim. IE. From jQuery library

http://api.jquery.com/jQuery.trim/

kaz
  • 1,943
  • 1
  • 13
  • 19
  • 4
    Importing all of jQuery just to get at a `.trim()` implementation would be pretty crazy. – Pointy Aug 22 '12 at 12:26
  • If `jQuery` is not mentioned by the OP, it's safer to assume it's not used. ) Otherwise, quite a nice recommendation overall to rely upon the established solutions instead of inventing your own. ) – raina77ow Aug 22 '12 at 12:27
  • of course importing jQuery just for one method is crazy. But its only an example. There are many implementations for trim method in multiple libraries. – kaz Aug 22 '12 at 12:29
0

You can use jQuery trim.

<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
        <pre id="original"></pre>
        <pre id="trimmed"></pre>
<script>
  var str = "         first second         ";
  $("#original").html("Original String: '" + str + "'");
  $("#trimmed").html("After trimed: '" + $.trim(str) + "'");
</script>

</body>
</html>
swemon
  • 5,840
  • 4
  • 32
  • 54
0

A litle modification for your pattern:

(^\s+|\s+$)

and then

var string = "     test     ";
string.replace(/(^\s+|\s+$)/gm, '');

should work ;-)

Adam Wolski
  • 5,448
  • 2
  • 27
  • 46