简体   繁体   English

如何替换javascript中单词之间的所有空格

[英]How can I replace all spaces between words in javascript

This should be simple bu I can't get it working. 这应该很简单,但是我无法正常工作。

The title pretty much explains it all. 标题几乎说明了一切。 I tried: 我试过了:

var tags = "best cars ever";
var hashtags = tags.replace("/\s/g", "");
document.write(hashtags);

and also: 并且:

var tags = "best cars ever";
var hashtags = tags.replace("/ /g", "");
document.write(hashtags);

When you use replace() with a regular expression, don't put that expression inside a string: 当将replace()与正则表达式一起使用时,请勿将该表达式放在字符串中:

 var tags = "best cars ever"; var hashtags = tags.replace(/\\s/g, ""); console.log(hashtags); 

var tags = "best cars ever";
tags.split(" ").join("");

You can use the RegExp constructor to creates a regular expression or literal. 您可以使用RegExp构造函数创建正则表达式或文字。 ( see bellow an example with RexExp constructor) (请参见下面的RexExp构造函数示例)

 var tags = "best cars ever"; var hashtags = tags.replace(new RegExp("\\\\s","g"), ""); console.log(hashtags); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript-如何替换数字和字母之间的所有空格 - Javascript - How do I replace all spaces that are only between a number and letter 我如何用 JavaScript 替换这些词? - How i can replace these words with JavaScript? 如何用正则表达式计算或替换 javascript 中 { } 或 [ ] 之间的所有匹配词? - How to count or replace all matching words between { } or [ ] in javascript with regex? 如何正则表达式用下划线替换匹配文本中的所有空格? (Javascript) - How can I regex replace all spaces in matched text with underscore? (Javascript) javascript - 用html标签替换所有空格以包含剩余的单词 - javascript - replace all white spaces with html tags to enclose remaining words Javascript正则表达式-删除字符串中除单词之间的所有空格 - Javascript regex- remove all spaces in string except between words 如何在 javascript 中用空格替换换行符/换行符? - How can I replace newlines/line breaks with spaces in javascript? 如何比较两个字符串并将匹配的单词替换为 JavaScript? - How can I compare two strings and replace matching words with JavaScript? 如何使用 javascript 替换语句中的几个单词? - How can I replace several words in a statement using javascript? 如何替换字符串中的单词并在 Javascript 中添加 id - How can I replace words in a string and add id in Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM