从文本中删除所有空格 [英] Remove ALL white spaces from text

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

问题描述


可能重复:

用'+'替换字符串中的所有空格





$("#topNav" + $("#breadCrumb2nd").text().replace(" ", "")).addClass("current");

这是我代码中的一个片段。我想在获取另一个ID的文本属性后向ID添加一个类。这个问题,是持有我需要的文本的ID,包含字母之间的间隙。

This is a snippet from my code. I want to add a class to an ID after getting another ID's text property. The problem with this, is the ID holding the text I need, contains gaps between the letters.

我想删除空格。我试过 TRIM() REPLACE()但这只是部分有效。 REPLACE()仅删除第一个空格。

I would like the white spaces removed. I have tried TRIM()and REPLACE() but this only partially works. The REPLACE() only removes the 1st space.

推荐答案

你有告诉replace()重复正则表达式:

You have to tell replace() to repeat the regex:

.replace(/ /g,'')

g 字符表示在整个字符串中重复搜索。阅读此内容以及JavaScript中提供的其他RegEx修饰符此处

The g character means to repeat the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.

如果要匹配所有空格,而不仅仅是文字空格字符,请改用 \s

If you want to match all whitespace, and not just the literal space character, use \s instead:

.replace(/\s/g,'')

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

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