Cec*_*ore 532 javascript jquery
可能重复:
用'+'替换字符串中的所有空格
$("#topNav" + $("#breadCrumb2nd").text().replace(" ", "")).addClass("current");
Run Code Online (Sandbox Code Playgroud)
这是我的代码中的一个片段.我想在获取另一个ID的文本属性后向ID添加一个类.这个问题,是持有我需要的文本的ID,包含字母之间的间隙.
我希望删除白色空格.我试过了TRIM(),REPLACE()但这只是部分有效.该REPLACE()只删除第一个空间.
Fli*_*mzy 1229
你必须告诉replace()重复正则表达式:
.replace(/ /g,'')
Run Code Online (Sandbox Code Playgroud)
该摹字是指通过重复整个字符串搜索.在此处阅读此处以及JavaScript中提供的其他RegEx修饰符.
如果要匹配所有空格,而不仅仅是文字空格字符,请\s改用:
.replace(/\s/g,'')
Run Code Online (Sandbox Code Playgroud)
Pan*_*lis 290
.replace(/\s+/, "")
Run Code Online (Sandbox Code Playgroud)
将仅替换第一个空格,包括空格,制表符和新行.
要替换字符串中的所有空格,您需要使用全局模式
.replace(/\s/g, "")
Run Code Online (Sandbox Code Playgroud)
Bal*_*aji 22
正则表达式用于删除空格
\s+
Run Code Online (Sandbox Code Playgroud)
或者
[ ]+
Run Code Online (Sandbox Code Playgroud)
var str = "Visit Microsoft!";
var res = str.replace(/\s+/g, "");
console.log(res);Run Code Online (Sandbox Code Playgroud)
删除字符串开头的所有空格
^[ ]+
Run Code Online (Sandbox Code Playgroud)
删除字符串末尾的所有空格
[ ]+$
Run Code Online (Sandbox Code Playgroud)
var str = "Visit Microsoft!";
var res = str.replace(/[ ]+/g, "");
console.log(res);Run Code Online (Sandbox Code Playgroud)
var mystring="fg gg";
console.log(mystring.replaceAll(' ',''))
Run Code Online (Sandbox Code Playgroud)
cam*_*777 11
现在你可以使用“replaceAll”:
console.log(' a b c d e f g '.replaceAll(' ',''));
Run Code Online (Sandbox Code Playgroud)
将打印:
abcdefg
Run Code Online (Sandbox Code Playgroud)
但不适用于所有可能的浏览器:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
Asi*_*kib 10
** 100% 工作
使用replace(/ +/g,'_'):
let text = "I love you"
text = text.replace( / +/g, '_') // replace with underscore ('_')
console.log(text) // I_love_youRun Code Online (Sandbox Code Playgroud)
我不明白为什么我们需要在这里使用正则表达式,而我们可以简单地使用replaceAll
let result = string.replaceAll(' ', '')
Run Code Online (Sandbox Code Playgroud)
result将存储string没有空格
String.prototype.replace如其他答案中所述,使用正则表达式当然是最好的解决方案。
但是,为了好玩,您还可以使用String.prototype.splitand删除文本中的所有空格String.prototype.join:
const text = ' a b c d e f g ';
const newText = text.split(/\s/).join('');
console.log(newText); // prints abcdefgRun Code Online (Sandbox Code Playgroud)