1、去除前面或后面的空格:
var str=" s ss "; console.log(str.replace(/^ +| +$/, '')); //s ss (去除前面的空格。若前有空格或前后都有空格,去除前面空格;若只有后面有空格,则去除后面空格) console.log(str.replace(/^\s+|\s+$/g, '')); //s ss(去除前后的空格) console.log(str.replace(/\s*$/, '')); // s ss(去除后面的空格) console.log(str.replace(/^\s*/, '')); //s ss (去除前面的空格) console.log(str.replace(/^\s*/, '').replace(/\s*$/, '')); //s ss(去除前后空格)
2、将“.”替换成“,”:
var str = "abc.ddd . djoi"; console.log(str.replace(/\./g, ',')); //abc,ddd , djoi
3、