Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - 我想从字符串中删除双引号(I want to remove double quotes from a String)

I want to remove the "" around a String.

(我想删除字符串周围的"" 。)

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

(例如,如果字符串为: "I am here"那么我只想输出I am here 。)

  ask by ankur translate from so

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

1 Answer

0 votes
by (71.8m points)

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)

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

  • g : the global flag.

    (g全局标志。)

    This tells JS to apply the regex to the entire string.

    (这告诉JS将正则表达式应用于整个字符串。)

    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

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

    (" :另一个文字,请参见清单项)

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.

(替换为'$1' ,这是对第一个捕获组的后向引用,为[^" ]+或双引号之间的所有内容。该模式既匹配引号,又包括引号之间的内容,但仅将其替换为引号之间是什么,从而有效地将其删除。)


What it does is some "string with" quotes -> replaces "string with" with -> string with .

(它所做的是some "string with" quotes - >替换"string 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');

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.

(使用输入remove "foo" delimiting " ,输出将保持不变,但是将输入字符串更改为"remove "foo" delimiting quotes" ,最后将以remove "foo" delimiting quotes作为输出。)

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.

    (如果字符串不是以"开头,则表达式在此处已经失败,并且不会替换任何内容。)

  • (.+(?="$)) : 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)

    ((?="$) :正向前瞻与上面的内容非常相似,只是它指定" 必须为字符串的结尾( $ === 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.

(您可能已经注意到,我省略了g标志(对于全局BTW),因为由于我们正在处理整个字符串,因此该表达式仅适用一次。)


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

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.

(如果是的话,我正在使用substr 切断那些第一个和最后一个字符。)

Strings are zero-indexed, so the last char is the charAt(str.length -1) .

(字符串是零索引的,因此最后一个char是charAt(str.length -1) 。)

substr expects 2 arguments, where the first is the offset from which the substring starts, the second is its length.

(substr需要2个参数,其中第一个是子字符串开始的偏移量,第二个是其长度。)

Since we don't want the last char, anymore than we want the first, that length is str.length - 2 .

(由于我们不想要最后一个字符,因此比我们想要的第一个字符长,该长度为str.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.

(正则表达式非常有用(和IMO一样有趣),乍一看可能令人费解。)

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

(如果字符串中的引号很多,这甚至比使用正则表达式更快)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...