Home  >  Q&A  >  body text

Remove leading and trailing quotes from user-submitted strings in VueJS

I have a VueJS application that contains forms that are pre-populated with data. The textarea element contains some data as shown on the UI

NOTE: (Sorry, I don't have enough rep points to attach a screenshot yet):

Screenshot of quoted UI text area element

I cannot modify the way the backend provides data.

So, is there a good way to remove the first and last quotes from a string? I don't want to touch the inner text in case the user adds quotes in it.

The expected output of

'Hello World,welcome to "fooWorld!"' should be Hello World,welcome to 'fooWorld!'

Here is a real-life example of how I use data in a SPA:

data() {
    return {
        entryNotes: this.post.entryNotes  //<--- this is the data I need to format
    }
}

P粉076987386P粉076987386206 days ago372

reply all(1)I'll reply

  • P粉930534280

    P粉9305342802024-03-27 15:27:18

    How to remove opening and closing quotes using fast regex?

    data(){
        return {
            entryNotes: this.post.entryNotes.replace(/^"/,"").replace(/"$/,"")
        }
    }

    The first regular expression looks for the beginning of the string (represented by ^), then for quotes. The second regex looks for quotes and then for the end of the string (the end of the string is represented by $).

    You can also do this:

    str.match(/^"?(.+?)"?$/)[1]

    This looks for the beginning of the string (^), followed by a ", but the ? makes it optional. Then the brackets capture . , which means match anything. The ? before the end of the bracket means stop matching as soon as possible. Then it says to look for quotes, but the next question mark says "maybe" and then looks for the end of the string ($).

    reply
    0
  • Cancelreply