javascript - Why have two '\' in Regex? -


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:

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

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - IIFE: var vs this - is there any difference? -

ios - Google API (YouTube search): Bad network response -