如何使用JavaScript从字符串中删除空格? [英] How to remove spaces from a string using JavaScript?

查看:185
本文介绍了如何使用JavaScript从字符串中删除空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何删除字符串中的空格?例如:

How to remove spaces in a string? For instance:

输入:'/ var / www / site /全新document.docx'

输出:'/ var / www / site / Brandnewdocument.docx'

谢谢

推荐答案

这个?

str = str.replace(/\s/g, '');

示例

var str = '/var/www/site/Brand new document.docx';

document.write( str.replace(/\s/g, '') );

更新:基于此问题,this:

str = str.replace(/\s+/g, '');

是一个更好的解决方案。它会产生相同的结果,但会更快。

is a better solution. It produces the same result, but it does it faster.

正则表达式

\s 是whitespace的正则表达式, g 是全局标志,意味着匹配ALL \s (空白)。

\s is the regex for "whitespace", and g is the "global" flag, meaning match ALL \s (whitespaces).

可以找到 + 的一个很好的解释这里

A great explanation for + can be found here.

作为旁注,你可以替换单引号和任何你想要的内容之间的内容,所以你可以用任何其他字符串替换空格。

As a side note, you could replace the content between the single quotes to anything you want, so you can replace whitespace with any other string.

这篇关于如何使用JavaScript从字符串中删除空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆