简体   繁体   中英

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. Using the replace() function, works for the strings that only have 2 " within the string but not 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 ".

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.

Here is my JavaScript code:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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