简体   繁体   English

将正则表达式添加到 Vue.js 数据对象

[英]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.我需要操作一个 URL,以便它删除最后一个/之后的所有内容,然后将我自己的文件名附加到末尾。

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.我尝试了下面 URL 中的代码,但挂载的功能似乎不起作用。 Not sure if that is because of Vue2 or not, as the post is 18 months old.不确定这是否是因为 Vue2,因为该帖子已有 18 个月的历史。

https://forum.vuejs.org/t/binding-a-regexp-object-to-an-html-attribute/815 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 .这是JSFiddle中的代码。

How can I incorporate the regex to convert the url to output in the HTML?如何合并正则表达式以将 url 转换为 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 ):您提到的正则表达式模式将匹配 URL 的最后一个路径段(即最后一个斜杠之后的文本)( demo 1 ),但代码注释表明您希望它匹配最后一个斜杠之前的所有内容,这将需要模式如下(演示 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:注意捕获组#1 包含您想要的 URL 部分,您可以按如下方式提取它:

 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 .您可以使用包含基于this.myimage中的字符串的有效URL计算属性 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 :在以下示例中, imgUrl计算属性解析this.myimage以确保它是有效的URL ,并使用正则表达式解析最后一个斜杠之前的文本,然后将其作为/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.myimage是无效 URL,则计算属性返回undefined 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 .这意味着如果文本输入包含xyzthis.imgUrl将是undefined的,但如果输入包含http://google.com/a/b/c http://google.com/a/b 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).考虑到这一点,我们将v-show变量替换为imgUrl ,以便<img>仅在定义了 imgUrl 且不为空时this.myimage imgUrl有效的 URL 字符串时)。 We also replace the value of v-bind:src with imgUrl , since it will already contain the full intended URL with /home.jpg appended:我们还将v-bind:src的值替换为imgUrl ,因为它已经包含了完整的预期 URL,并附加了/home.jpg

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

updated jsFiddle更新了 jsFiddle

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

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