Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

javascript - 从文本中删除所有空格[复制](Remove ALL white spaces from text [duplicate])

Possible Duplicate:

(可能重复:)
Replace all spaces in a string with '+'

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

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

This is a snippet from my code.

(这是我的代码中的一个片段。)

I want to add a class to an ID after getting another ID's text property.

(我想在获取另一个ID的文本属性后向ID添加一个类。)

The problem with this, is the ID holding the text I need, contains gaps between the letters.

(这个问题,是持有我需要的文本的ID,包含字母之间的间隙。)

I would like the white spaces removed.

(我希望删除白色空格。)

I have tried TRIM() and REPLACE() but this only partially works.

(我已经尝试过TRIM()REPLACE()但这只是部分有效。)

The REPLACE() only removes the 1st space.

(REPLACE()仅删除第一个空格。)

  ask by Cecil Theodore translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

.replace(/ /g,'')

The g character means to repeat the search through the entire string.

(g字符表示在整个字符串中重复搜索。)

Read about this, and other RegEx modifiers available in JavaScript here .

(在此处阅读此处以及JavaScript中提供的其他RegEx修饰符。)

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

(如果要匹配所有空格,而不仅仅是文字空格字符,请使用\s代替:)

.replace(/s/g,'')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...