例如:我有一个类似的字符串:" Text is text "
。
现在我想使用Javascript删除该字符串之前和之后的所有空格以获得结果:
"Text is text"
。
我怎么能用Javascript。谢谢你的帮助。
答案 0 :(得分:3)
答案 1 :(得分:3)
使用String.trim
(IE 9+和普通浏览器)。
" my text ".trim(); // "my text"
要确保它可以在所有浏览器中使用,您可以使用正则表达式:
var str,
re;
str = " my text ";
re = /^\s+|\s+$/g;
console.log(str.replace(re, ''));
答案 2 :(得分:1)
var text = " Text is text ".
var res = text.replace(/(^(\s+)|(\s+)$)/g,function(spaces){ return spaces.replace(/\s/g,"");});
console.log(res);
试试这个。
答案 3 :(得分:1)
试试吧,
var str = " Text is text ";
str = str.replace(/(^\s+|\s+$)/g, '');
答案 4 :(得分:1)
你可以在结尾和开头使用str.trim()
个空格,如果你想在单词之间留出不需要的空格,你可以使用正则表达式删除
" my text ".trim(); => "my text"
" my text".replace("/ {2,}/g"," "); => "my text"
" my text ".trim().replace("/ {2,}/g"," "); => "my text"