我想从字符串中删除双引号

时间:2022-09-15 13:10:45

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.

如果字符串是:“I am here”,那么我想输出的就是“I am here”。

10 个解决方案

#1


242  

Assuming:

假设:

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).

这应该能达到目的……(如果你的目标是替换所有双引号)。

Here's how it works:

它是如何工作的:

  • ['"] 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)
  • +:一个或多个引号,chars,由前面的char类定义(可选)
  • 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.
  • g:全球国旗。这告诉JS将regex应用到整个字符串。如果省略这个,只会替换一个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:

如果您试图删除给定字符串(即成对)的引号,事情就会变得有点棘手。你必须使用lookaround断言:

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

Regex explained:

正则表达式解释道:

  • ": 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
  • [^ "]+:字符类,匹配所有字符,除了“1次或更多
  • (?="): 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
  • :另一个文字,cf列表项目1

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.

替代“$ 1”,这是一个指向所捕获的第一集团,”[^]+,或者你可以在双引号之间。模式匹配引号和它们之间的内容,但只使用引号之间的内容替换,从而有效地删除它们。它所做的就是用引号将字符串替换为->字符串。报价走了,工作。

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

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

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

With input remove "foo" delimiting ", the output will remain unchanged, but change the input string to "remove "foo" delimiting quotes", and you'll end up with remove "foo" delimiting quotes as output.

输入删除“foo”分隔符,输出将保持不变,但是将输入字符串更改为“remove”foo“delimit引号”,最后将删除“foo”分隔引号作为输出。

Explanation:

解释:

  • ^": 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.
  • ^”:匹配字符串的开始^和“。如果字符串不是以a开头的,那么表达式在这里就已经失败了,并且没有任何内容被替换。
  • (.+(?="$)): 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
  • $:匹配结束引用,但不捕获它

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:

替换的方法和以前一样:我们替换匹配(包括打开和结束引号),以及它们内部的所有内容。您可能已经注意到我省略了g标志(对于global BTW),因为由于我们正在处理整个字符串,所以这个表达式只应用一次。一种更简单的regex,几乎是相同的东西(regex是如何编译/应用的内部差异):

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:

像以前一样^”和“匹配美元限定引用字符串的开始和结束,和(+)匹配之间的一切,并捕捉它。我已经尝试过这个regex,与上面的那个(带有前瞻性断言)并列,而且不可否认地,令我惊讶的是,我发现这个有点慢。我的猜测是,在引擎确定字符串末尾不存在时,lookaround断言会导致前面的表达式失败。嗯,但是如果这是你想要的/需要的,请继续读:

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));
}

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.

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

Tips:

小贴士:

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:

关于查找断言的更多信息可以在这里找到,Regex的断言非常有用(在我看来很有趣),一开始可能有点令人困惑。这里有更多的细节,以及相关资源的链接。如果您还不太喜欢使用regex,您可以考虑使用:

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

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

如果字符串中有很多引号,这甚至可能比使用regex还要快

#2


53  

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

This regexp will only remove the quotes if they are the first and last characters of the string. F.ex:

这个regexp将只删除引号,如果它们是字符串的第一个和最后一个字符。F.ex:

"I am here"  => I am here (replaced)
I "am" here  => I "am" here (untouched)
I am here"   => I am here" (untouched)

#3


16  

If you have control over your data ... say with :

如果你能控制你的数据……说:

"20151212211647278"

or similar this nicely removes the quotes

或者类似的,很好地删除了引号。

JSON.parse("20151212211647278");

Not a universal answer however slick for niche needs

这不是一个通用的答案,但对于利基市场的需求来说,这是一个非常巧妙的解决方案。

#4


9  

If you only want to remove the boundary quotes:

如果您只想删除边界引号:

function stripquotes(a) {
    if (a.charAt(0) === '"' && a.charAt(a.length-1) === '"') {
        return a.substr(1, a.length-2);
    }
    return a;
}

This approach won't touch the string if it doesn't look like "text in quotes".

如果字符串看起来不像“引号中的文本”,这种方法就不会触及字符串。

#5


6  

If the string is guaranteed to have one quote (or any other single character) at beginning and end which you'd like to remove:

如果字符串在开始和结束时保证有一个引号(或任何其他单个字符),您想要删除:

str = str.slice(1, -1);

slice has much less overhead than a regular expression.

slice的开销要比正则表达式小得多。

#6


5  

If you only want to remove quotes from the beginning or the end, use the following regular expression:

如果您只想从开头或结尾删除引号,请使用以下正则表达式:

'"Hello"'.replace(/(^"|"$)/g, '');

#7


5  

To restate your problem in a way that's easier to express as a regular expression:

用一种更容易用正则表达式来表达的方式重新陈述你的问题:

Get the substring of characters that is contained between zero or one leading double-quotes and zero or one trailing double-quotes.

获取包含在0或1个前导双引号和0或1个尾双引号之间的字符的子字符串。

Here's the regexp that does that:

这里是regexp:

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

Breaking down the regexp:

打破regexp:

  • ^"? a greedy match for zero or one leading double-quotes
  • ^”?对零或一个前置双引号的贪婪匹配
  • "?$ a greedy match for zero or one trailing double-quotes
  • ”?$一个贪婪的匹配为零或一个尾双引号
  • those two bookend a non-greedy capture of all other characters, (.+?), which will contain the target as $1.
  • 这两个书签是对所有其他字符(.+?)的非贪婪捕获,它将目标包含为$1。

This will return delimited "string" here for:

这将返回带分隔符的“字符串”:

str = "delimited "string" here"  // ...
str = '"delimited "string" here"' // ...
str = 'delimited "string" here"' // ... and
str = '"delimited "string" here'

#8


3  

A one liner for the lazy people

懒汉们的一句俏皮话

var str = '"a string"';
str = str.replace(/^"|"$/g, '');

#9


0  

If you want to remove all double quotes in string, use

如果要删除字符串中的所有双引号,请使用

var str = '"some "quoted" string"';
console.log( str.replace(/"/g, '') );
// some quoted string

Otherwise you want to remove only quotes around the string, use:

否则,要删除字符串周围的引号,请使用:

var str = '"some "quoted" string"';
console.log( clean = str.replace(/^"|"$/g, '') );
// some "quoted" string

#10


0  

This simple code will also work, to remove for example double quote from a string surrounded with double quote:

这个简单的代码也可以使用,例如,从一个字符串中删除双引号:

var str = 'remove "foo" delimiting double quotes';
console.log(str.replace(/"(.+)"/g, '$1'));

#1


242  

Assuming:

假设:

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).

这应该能达到目的……(如果你的目标是替换所有双引号)。

Here's how it works:

它是如何工作的:

  • ['"] 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)
  • +:一个或多个引号,chars,由前面的char类定义(可选)
  • 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.
  • g:全球国旗。这告诉JS将regex应用到整个字符串。如果省略这个,只会替换一个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:

如果您试图删除给定字符串(即成对)的引号,事情就会变得有点棘手。你必须使用lookaround断言:

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

Regex explained:

正则表达式解释道:

  • ": 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
  • [^ "]+:字符类,匹配所有字符,除了“1次或更多
  • (?="): 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
  • :另一个文字,cf列表项目1

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.

替代“$ 1”,这是一个指向所捕获的第一集团,”[^]+,或者你可以在双引号之间。模式匹配引号和它们之间的内容,但只使用引号之间的内容替换,从而有效地删除它们。它所做的就是用引号将字符串替换为->字符串。报价走了,工作。

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

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

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

With input remove "foo" delimiting ", the output will remain unchanged, but change the input string to "remove "foo" delimiting quotes", and you'll end up with remove "foo" delimiting quotes as output.

输入删除“foo”分隔符,输出将保持不变,但是将输入字符串更改为“remove”foo“delimit引号”,最后将删除“foo”分隔引号作为输出。

Explanation:

解释:

  • ^": 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.
  • ^”:匹配字符串的开始^和“。如果字符串不是以a开头的,那么表达式在这里就已经失败了,并且没有任何内容被替换。
  • (.+(?="$)): 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
  • $:匹配结束引用,但不捕获它

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:

替换的方法和以前一样:我们替换匹配(包括打开和结束引号),以及它们内部的所有内容。您可能已经注意到我省略了g标志(对于global BTW),因为由于我们正在处理整个字符串,所以这个表达式只应用一次。一种更简单的regex,几乎是相同的东西(regex是如何编译/应用的内部差异):

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:

像以前一样^”和“匹配美元限定引用字符串的开始和结束,和(+)匹配之间的一切,并捕捉它。我已经尝试过这个regex,与上面的那个(带有前瞻性断言)并列,而且不可否认地,令我惊讶的是,我发现这个有点慢。我的猜测是,在引擎确定字符串末尾不存在时,lookaround断言会导致前面的表达式失败。嗯,但是如果这是你想要的/需要的,请继续读:

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));
}

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.

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

Tips:

小贴士:

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:

关于查找断言的更多信息可以在这里找到,Regex的断言非常有用(在我看来很有趣),一开始可能有点令人困惑。这里有更多的细节,以及相关资源的链接。如果您还不太喜欢使用regex,您可以考虑使用:

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

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

如果字符串中有很多引号,这甚至可能比使用regex还要快

#2


53  

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

This regexp will only remove the quotes if they are the first and last characters of the string. F.ex:

这个regexp将只删除引号,如果它们是字符串的第一个和最后一个字符。F.ex:

"I am here"  => I am here (replaced)
I "am" here  => I "am" here (untouched)
I am here"   => I am here" (untouched)

#3


16  

If you have control over your data ... say with :

如果你能控制你的数据……说:

"20151212211647278"

or similar this nicely removes the quotes

或者类似的,很好地删除了引号。

JSON.parse("20151212211647278");

Not a universal answer however slick for niche needs

这不是一个通用的答案,但对于利基市场的需求来说,这是一个非常巧妙的解决方案。

#4


9  

If you only want to remove the boundary quotes:

如果您只想删除边界引号:

function stripquotes(a) {
    if (a.charAt(0) === '"' && a.charAt(a.length-1) === '"') {
        return a.substr(1, a.length-2);
    }
    return a;
}

This approach won't touch the string if it doesn't look like "text in quotes".

如果字符串看起来不像“引号中的文本”,这种方法就不会触及字符串。

#5


6  

If the string is guaranteed to have one quote (or any other single character) at beginning and end which you'd like to remove:

如果字符串在开始和结束时保证有一个引号(或任何其他单个字符),您想要删除:

str = str.slice(1, -1);

slice has much less overhead than a regular expression.

slice的开销要比正则表达式小得多。

#6


5  

If you only want to remove quotes from the beginning or the end, use the following regular expression:

如果您只想从开头或结尾删除引号,请使用以下正则表达式:

'"Hello"'.replace(/(^"|"$)/g, '');

#7


5  

To restate your problem in a way that's easier to express as a regular expression:

用一种更容易用正则表达式来表达的方式重新陈述你的问题:

Get the substring of characters that is contained between zero or one leading double-quotes and zero or one trailing double-quotes.

获取包含在0或1个前导双引号和0或1个尾双引号之间的字符的子字符串。

Here's the regexp that does that:

这里是regexp:

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

Breaking down the regexp:

打破regexp:

  • ^"? a greedy match for zero or one leading double-quotes
  • ^”?对零或一个前置双引号的贪婪匹配
  • "?$ a greedy match for zero or one trailing double-quotes
  • ”?$一个贪婪的匹配为零或一个尾双引号
  • those two bookend a non-greedy capture of all other characters, (.+?), which will contain the target as $1.
  • 这两个书签是对所有其他字符(.+?)的非贪婪捕获,它将目标包含为$1。

This will return delimited "string" here for:

这将返回带分隔符的“字符串”:

str = "delimited "string" here"  // ...
str = '"delimited "string" here"' // ...
str = 'delimited "string" here"' // ... and
str = '"delimited "string" here'

#8


3  

A one liner for the lazy people

懒汉们的一句俏皮话

var str = '"a string"';
str = str.replace(/^"|"$/g, '');

#9


0  

If you want to remove all double quotes in string, use

如果要删除字符串中的所有双引号,请使用

var str = '"some "quoted" string"';
console.log( str.replace(/"/g, '') );
// some quoted string

Otherwise you want to remove only quotes around the string, use:

否则,要删除字符串周围的引号,请使用:

var str = '"some "quoted" string"';
console.log( clean = str.replace(/^"|"$/g, '') );
// some "quoted" string

#10


0  

This simple code will also work, to remove for example double quote from a string surrounded with double quote:

这个简单的代码也可以使用,例如,从一个字符串中删除双引号:

var str = 'remove "foo" delimiting double quotes';
console.log(str.replace(/"(.+)"/g, '$1'));