我想把所有的表达式组合成一个,但我不知道怎么做,它需要去掉结尾的空格和开头的空格,但要把两个单词之间的空格缩短到只有一个(如果有多个单词)。谢谢
var _str = document.contact_form.contact_name.value;
name_str = _str.replace(/\s+/g,' ');
str_name = name_str.replace(/\s+$/g,'');
name = str_name.replace(/^\s+/g,'');
document.contact_form.contact_name.value = name;发布于 2011-11-03 14:08:48
您可以将后两个组合为一个正则表达式:
name = _str.replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '');您还可以查看jQuery的trim方法。
说明:删除字符串开头和结尾的空格。
发布于 2011-11-03 14:11:16
var name = _str.replace(/\s+$|^\s+/g,'').replace(/\s+/g,' '); 您可以在正则表达式中使用|字符来匹配其两边的子表达式,并且可以将多个调用链接到.replace()。
顺便说一句,别忘了用var声明所有变量。
发布于 2011-11-03 14:08:52
document.contact_form.contact_name.value = _str.replace(/\s+/g,' ')..replace(/\s+$/g,'').replace(/^\s+/g,'');https://stackoverflow.com/questions/7990879
复制相似问题