简体   繁体   English

用JavaScript替换4字符之间的字符串中的字符串

[英]Replacing pieces of strings within a string between 4 " characters in JavaScript

​ In JavaScript, I have an automatically generated array of strings (through an GET request) that have the character " within a string. My aim is to remove all the text within two " in a single string. 在JavaScript中,我有一个自动生成的字符串数组(通过GET请求),在字符串中包含字符``。我的目的是删除单个字符串中两个''内的所有文本。 Using the replace() function, works for the strings that only have 2 " within the string but not 4. 使用replace()函数,可处理字符串中仅包含2“而不是4的字符串。

For strings that have 4 " (two pieces of text that need to be removed), array[3] in example below, the replace() function removes too much text. It removes all the text found between the first " and last ", while it should remove the text between the first & second " AND between the third & fourth ". 对于下面示例中的array[3] ,具有4“(需要删除两段文本)的字符串, replace()函数将删除过多的文本。它将删除在第一个“和最后一个”之间找到的所有文本,而应删除第一和第二“与”第三和第四“之间的文本。

Would anybody know a solution for this? 有人知道解决方案吗?

Please note: The array which I use in my code is generated automatically from somewhere else. 请注意:我在代码中使用的数组是从其他地方自动生成的。 Changing the array of strings manually is not possible. 不能手动更改字符串数组。 For the script below and in the Fiddle I use escape character \\ to include the " within the string, but in my actual array these are not present. 对于下面和Fiddle中的脚本,我使用转义符\\来在字符串中包含“”,但是在我的实际数组中不存在这些字符。

Here is my JavaScript code: 这是我的JavaScript代码:

var array = ["John Mayer & Peter Right", "John \"the Man\" Mayer & Peter Right", "John Mayer & Peter \"the King\" Right", "John \"the Man\" Mayer & Peter \"the King\" Right"]
new_array = []
    for (var i = 0; i < array.length; i++){
        var edit_string = array[i].replace(/".*"/, "")
        new_array.push(edit_string)
    }
console.log(new_array) // ["John Mayer & Peter Right", "John  Mayer & Peter Right", "John Mayer & Peter  Right", "John  Right"]

I have a working Fiddle that returns the wrong array of strings. 我有一个工作的小提琴 ,它返回错误的字符串数组。

Im not an regex expert. 我不是正则表达式专家。 I would do this with plain js: 我会用纯js来做到这一点:

console.log(array.map(e=>e.split("\"").map((a,i)=>i%2==0?a:undefined).join("")));

Split with ", then remove every second part of the array. 用“”分割,然后删除数组的第二部分。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM