简体   繁体   中英

Adding Regex to a Vue.js Data Object

I need to manipulate a URL so that it removes everything after the last / and then I append my own filename to the end.

The regex to remove everything after the final / is [^\/]+$ .

I tried the code from the URL below but the mounted function doesn't seem to work. Not sure if that is because of Vue2 or not, as the post is 18 months old.

https://forum.vuejs.org/t/binding-a-regexp-object-to-an-html-attribute/815

    var vm = new Vue({
        el: '#vue-instance',
        data: {
            myimage: ''
        }
        });
        
    /* Regex to add is [^\/]+$ */

Here is the code in a JSFiddle .

How can I incorporate the regex to convert the url to output in the HTML?

Regex pattern

The regex pattern you mention would match the last path segment of the URL (ie, the text after the last slash) ( demo 1 ), but the code comment indicates you want it to match everything before the last slash, which would instead require a pattern like the following ( demo 2 ):

^(.+)\/.*$

Explanation of regex pattern broken down:

^    # assert position at start of line
(    # Start group 1
.+   # match any character (except line terminators), one or more times
)    # End group 1
\/   # match `/` literally
.*   # match any character (except line terminators), zero or more times
$    # assert position at end of line

Notice capture group #1 contains the URL parts you want, and you could extract it as follows:

 const url = 'https://google.com/foo/bar'; const regex = /^(.+)\/.*$/ig; const matches = regex.exec(url); console.log(matches[1]) /* 1 = group index */

Computed property

You could use acomputed property that would contain a valid URL based on the string in this.myimage . In the following example, the imgUrl computed property parses this.myimage to ensure it's a valid URL , and uses a regular expression to parse the text before the last slash, which it then prefixes to /home.jpg :

computed: {
  imgUrl() {
    let url = this.myimage;

    // validate URL in `this.myimage`
    try {
      url = new URL(url).toString();
    } catch (e) {
      url = '';
    }

    if (url) {
      const regex = /^(.+)\/.*$/ig;
      const matches = regex.exec(url);
      return matches && `${matches[1]}/home.jpg`;
    }
  }
}

Note the computed property returns undefined if this.myimage is an invalid URL. This means this.imgUrl would be undefined if the text input contained xyz , but it would be http://google.com/a/b if the input had http://google.com/a/b/c . With that in mind, we replace the v-show variable with imgUrl so that the <img> is only shown when imgUrl is defined and not empty (ie, when this.myimage is a valid URL string). We also replace the value of v-bind:src with imgUrl , since it will already contain the full intended URL with /home.jpg appended:

<img v-show="imgUrl" v-bind:src="imgUrl">

updated jsFiddle

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