我想从String中删除双引号 [英] I want to remove double quotes from a String

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

问题描述

我想删除字符串周围的

I want to remove the "" around a String.

例如。如果字符串是:我在这里那么我只想输出我在这里

e.g. if the String is: "I am here" then I want to output only I am here.

推荐答案

假设:

var someStr = 'He said "Hello, my name is Foo"';
console.log(someStr.replace(/['"]+/g, ''));

这应该可以解决问题......(如果你的目标是替换所有双引号)。

That should do the trick... (if your goal is to replace all double quotes).

这是怎么回事作品:


  • ['] 是一个字符类,匹配单个和双引号。你可以用替换它来匹配双引号。

  • + :一个或多个引号,字符,由前面的char类定义(可选)

  • g 全局标志。这告诉JS将正则表达式应用于整个字符串。如果省略这个,你只能替换一个字符。

  • ['"] is a character class, matches both single and double quotes. you can replace this with " to only match double quotes.
  • +: one or more quotes, chars, as defined by the preceding char-class (optional)
  • g: the global flag. This tells JS to apply the regex to the entire string. If you omit this, you'll only replace a single char.

如果你试图删除给定字符串周围的引号(即成对),事情会变得有点棘手。你将不得不使用外观断言:

If you're trying to remove the quotes around a given string (ie in pairs), things get a bit trickier. You'll have to use lookaround assertions:

var str = 'remove "foo" delimiting double quotes';
console.log(str.replace(/"([^"]+(?="))"/g, '$1'));
//logs remove foo delimiting quotes
str = 'remove only "foo" delimiting "';//note trailing " at the end
console.log(str.replace(/"([^"]+(?="))"/g, '$1'));
//logs remove only foo delimiting "<-- trailing double quote is not removed

正则表达式解释:


  • :literal,匹配任何文字

  • :开始捕获组。将捕获括号之间的任何内容(()),并且可以在替换值中使用。

  • [^] + :字符类,匹配所有字符,除了 1次或更多次

  • (?=):零宽度(如未捕获)正前瞻断言。前一个匹配仅在有效时才有效然后是文字

  • :结束捕获组,我们'我们在开幕式结束之间捕获了所有内容

  • :另一个文字,cf list item one

  • ": literal, matches any literal "
  • (: begin capturing group. Whatever is between the parentheses (()) will be captured, and can be used in the replacement value.
  • [^"]+: Character class, matches all chars, except " 1 or more times
  • (?="): zero-width (as in not captured) positive lookahead assertion. The previous match will only be valid if it's followed by a " literal
  • ): end capturing group, we've captured everything in between the opening closing "
  • ": another literal, cf list item one

替换为'$ 1',这是对第一个捕获组的反向引用, [^] + ,或双引号之间的每一个。模式匹配引号和它们之间的内容,但是只用引号之间的内容替换它,从而有效地删除它们。

它的作用是一些字符串机智h引号 - >将字符串替换为 - > 字符串。报价消失,完成工作。

The replacement is '$1', this is a back-reference to the first captured group, being [^" ]+, or everyting in between the double quotes. The pattern matches both the quotes and what's inbetween them, but replaces it only with what's in between the quotes, thus effectively removing them.
What it does is some "string with" quotes -> replaces "string with" with -> string with. Quotes gone, job done.

如果引号总是将在字符串的开头和结尾处,那么你可以使用这个:

If the quotes are always going to be at the begining and end of the string, then you could use this:

str.replace(/^"(.+(?="$))"$/, '$1');

输入 删除foo分隔符 ,输出将保持不变,但将输入字符串更改为 removefoodelimiting quotes ,并且你最终将删除foo分隔引号作为输出。

说明:


  • ^:匹配字符串的开头 ^ 。如果字符串不是以开头,那么表达式在此处已经失败,并且没有任何内容被替换。

  • (。+(?=$)):匹配(并捕获)所有内容,包括双引号一次或多次,前提是前瞻为真

  • (?=$):正向前瞻与上面大致相同,只是它指定 必须是字符串的结尾( $ === end)

  • $ :匹配结束报价,但不捕获它

  • ^": matches the beginning of the string ^ and a ". If the string does not start with a ", the expression already fails here, and nothing is replaced.
  • (.+(?="$)): matches (and captures) everything, including double quotes one or more times, provided the positive lookahead is true
  • (?="$): the positive lookahead is much the same as above, only it specifies that the " must be the end of the string ($ === end)
  • "$: matches that ending quote, but does not capture it

替换是在和以前一样:我们将匹配(包括开始和结束引号)替换为其中的所有内容。

您可能已经注意到我省略了 g flag(对于全局BTW),因为我们正在处理整个字符串,所以这个表达式只应用一次。

一个更简单的正则表达式,几乎可以做同样的事情(有内部差异如何编译/应用正则表达式将是:

The replacement is done in the same way as before: we replace the match (which includes the opening and closing quotes), with everything that was inside them.
You may have noticed I've omitted the g flag (for global BTW), because since we're processing the entire string, this expression only applies once.
An easier regex that does, pretty much, the same thing (there are internal difference of how the regex is compiled/applied) would be:

someStr.replace(/^"(.+)"$/,'$1');

和以前一样 ^$ 匹配字符串开头和结尾的分隔引号,而(。+)匹配其间的所有内容,并且抓住它。我已经尝试过这个正则表达式,与上面的一个(带有前瞻性断言)并且,不可否认,我的惊喜发现这个有点慢。我的猜测是,当引擎确定字符串末尾没有时,环绕声断言会导致前一个表达式失败。好吧,但是如果这样的话是你想要/需要的,请阅读

As before ^" and "$ match the delimiting quotes at the start and end of a string, and the (.+) matches everything in between, and captures it. I've tried this regex, along side the one above (with lookahead assertion) and, admittedly, to my surprize found this one to be slightly slower. My guess would be that the lookaround assertion causes the previous expression to fail as soon as the engine determines there is no " at the end of the string. Ah well, but if this is what you want/need, please do read on:

然而,在最后一种情况下,它更安全,更快速,更易于维护最好这样做:

However, in this last case, it's far safer, faster, more maintainable and just better to do this:

if (str.charAt(0) === '"' && str.charAt(str.length -1) === '"')
{
    console.log(str.substr(1,str.length -2));
}

在这里,我正在检查字符串中的第一个和最后一个字符是否是双引号。如果是,我是使用 substr 切断那些第一个和最后一个字符。字符串是零索引的,所以最后一个字符是 charAt(str.length -1) substr 需要2个参数,其中第一个是子串开始的偏移量,第二个是它的长度。因为我们不想要最后一个字符,所以比我们想要的第一个,那个长度是 str.length - 2 。 Easy-peazy。

Here, I'm checking if the first and last char in the string are double quotes. If they are, I'm using substr to cut off those first and last chars. Strings are zero-indexed, so the last char is the charAt(str.length -1). substr expects 2 arguments, where the first is the offset from which the substring starts, the second is its length. Since we don't want the last char, anymore than we want the first, that length is str.length - 2. Easy-peazy.

提示

关于环绕声断言的更多信息可在此处找到

正则表达式非常有用(和IMO乐趣),起初可能有些困惑。有关此事的以下是更多详细信息和资源链接。 b $ b如果您对使用正则表达式感到不舒服,可能需要考虑使用:

More on lookaround assertions can be found here
Regex's are very useful (and IMO fun), can be a bit baffeling at first. Here's some more details, and links to resources on the matter.
If you're not very comfortable using regex's just yet, you might want to consider using:

var noQuotes = someStr.split('"').join('');

如果有很多报价字符串,这甚至可能比使用正则表达式

If there's a lot of quotes in the string, this might even be faster than using regex

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

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