javascript - Why have two '\' in Regex? -
this question has answer here:
function trim(str) { var trimer = new regexp("(^[\\s\\t\\xa0\\u3000]+)|([\\u3000\\xa0\\s\\t]+\x24)", "g"); return string(str).replace(trimer, ""); } why have 2 '\' before 's' , 't'?
and what's "[\s\t\xa0\u3000]" mean?
why have 2 '\' before 's' , 't'?
in regex \ escape tells regex special character follows. because using in string literal need escape \ \.
and what's "[\s\t\xa0\u3000]" mean?
it means match 1 of following characters:
- \s white space.
- \t tab character.
- \xa0 non breaking space.
- \u3000 wide space.
this function inefficient because each time called converting string regex , compiling regex. more efficient use regex literal not string , compile regex outside function following:
var trimregex = /(^[\s\t\xa0\u3000]+)|([\u3000\xa0\s\t]+$)/g; function trim(str) { return string(str).replace(trimregex, ""); } further \s match whitespace includes tabs, wide space , non breaking space simplify regex following:
var trimregex = /(^\s+)|(\s+$)/g; browsers implement trim function can use , use polyfill older browsers. see answer
Comments
Post a Comment