1
function trim(str) {

    var trimer = new RegExp("(^[\\s\\t\\xa0\\u3000]+)|([\\u3000\\xa0\\s\\t]+\x24)", "g");

    return String(str).replace(trimer, "");

}

why have two '\' before 's' and 't'?

and what's this "[\s\t\xa0\u3000]" mean?

Liam
  • 27,717
  • 28
  • 128
  • 190
sunhua
  • 63
  • 7
  • it is two backslashes because a single backslash has a special meaning in Javascript. Because of this you need to "escape" the backslash – Marged Jun 15 '15 at 10:50
  • We should find a better QA for closing as duplicate. This one is too different (but I'm sure it's a duplicate) – Denys Séguret Jun 15 '15 at 10:55
  • Best I could find @DenysSéguret, I guess they've all been jumped on as too simple.. – Liam Jun 15 '15 at 10:57

2 Answers2

5

You're using a literal string.

In a literal string, the \ character is used to escape some other chars, for example \n (a new line) or \" (a double quote), and it must be escaped itself as \\. So when you want your string to have \s, you must write \\s in your string literal.

Thankfully JavaScript provides a better solution, Regular expression literals:

var trimer = /(^[\s\t\xa0\u3000]+)|([\u3000\xa0\s\t]+\x24)/g
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
3

why have two '\' before 's' and 't'?

In regex the \ is an escape which tells regex that a special character follows. Because you are using it in a string literal you need to escape the \ with \.

and what's this "[\s\t\xa0\u3000]" mean?

It means to match one of the following characters:

This function is inefficient because each time it is called it is converting a string to a regex and then it is compiling that regex. It would be more efficient to use a Regex literal not a string and compile the regex outside the function like the following:

var trimRegex = /(^[\s\t\xa0\u3000]+)|([\u3000\xa0\s\t]+$)/g;

function trim(str) {
    return String(str).replace(trimRegex, "");
}

Further to this \s will match any whitespace which includes tabs, the wide space and the non breaking space so you could simplify the regex to the following:

var trimRegex = /(^\s+)|(\s+$)/g;

Browsers now implement a trim function so you can use this and use a polyfill for older browsers. See this Answer

Community
  • 1
  • 1
Jack Allan
  • 14,554
  • 11
  • 45
  • 57