删除javascript中的字符串,不留空格

Delete a string in javascript, without leaving an empty space?

本文关键字:空格 字符串 javascript 删除      更新时间:2023-09-26

我见过多个此类问题的实例,但不是我要特别寻找的那个。。。(我只是希望我不是盲目的!:P)

让我们考虑一下这个代码:

var oneString = "This is a string";
document.write(oneString.replace("is", ""));

我本以为输出会是:

This a string.

但这是我得到的输出:

This a  string

这就像replace()认为发送的第二个参数是"而不是"。。。那么,在输出中没有多余的空格的情况下,剥离给定字符串的字符串的正确方式是什么?

您实际得到的是用空字符串替换的"is",它是之前的之后的.您替换的"是"保留为您看到的两个空格。尝试

oneString.replace("is ", "")

您确定没有得到"This a string"吗?

我认为您应该将"is"替换为",以获得您想要的输出。单词前后都有空格。

查看原始字符串-"This_is_a_string"(我用下划线替换了空格)。当你删除"is"时,你不会触摸周围的任何一个空格,所以两者都会出现在输出中。您需要做的是oneString.replace("is","").replace(/ +/," ")——去掉"is",然后消除任何双空格。如果你想保留一些双空格,请尝试oneString.replace(" is",""),尽管如果字符串以is开头(例如"它安全吗?"),你会遇到问题。

最好的答案可能是类似oneString.replace(/is ?/,"") to match is possibly followed by a space or的oneString.replace(/?是?/,")可能被空格包围,并用一个空格替换所有空格。

您的模式中没有包含任何空格。当我在Chrome中尝试你的代码时,我会得到:

> "This is a string".replace("is","")
  "Th is a string"

实现您尝试的一种方法是使用regexp:

> "This is a string".replace(/is's/,"")
  "This a string"
var aString = "This is a string";
var find = "is";    // or 'This' or 'string'
aString = aString.replace(new RegExp("(^|''s+)" + find + "(''s+|$)", "g"), "$1");
console.log(oneString);

唯一不完美的情况是,当你替换句子中的最后一个单词时。它会在最后留下一个空格,但我想你可以检查一下。

g修饰符用于使replace替换所有实例,而不仅仅是第一个实例。

添加i修饰符使其不区分大小写。

如果你也想在字符串上工作,比如:

"This has a comma, in it"

将正则表达式更改为:

var find = "comma";
new RegExp("(^|''s+)" + find + "(''s+|$|,)", "g")