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

标签 javascript regex vue.js vuejs2 vue-component

我需要操作一个 URL,以便它删除最后一个 / 之后的所有内容,然后我将自己的文件名附加到末尾。

在最后的 / 之后删除所有内容的正则表达式是 [^\/]+$

我尝试了以下 URL 中的代码,但安装的函数似乎不起作用。不确定这是不是因为 Vue2,因为该帖子已有 18 个月了。

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 [^\/]+$ */

这是 JSFiddle 中的代码.

如何合并正则表达式以将 url 转换为 HTML 输出?

最佳答案

正则表达式模式

您提到的正则表达式模式将匹配 URL 的最后一个路径段(即最后一个斜线之后的文本)(demo 1),但代码注释表明您希望它匹配 最后一个斜线之前的所有内容,这将需要类似以下的模式 (demo 2):

^(.+)\/.*$

正则表达式模式分解的解释:

^    # 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

公告capture group #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将包含有效的 URL 基于 this.myimage 中的字符串.在以下示例中,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`;
    }
  }
}

注意计算属性返回 undefined如果this.myimage是一个无效的 URL。这意味着 this.imgUrl将是 undefined如果文本输入包含 xyz , 但它将是 http://google.com/a/b如果输入有 http://google.com/a/b/c .考虑到这一点,我们替换了 v-show变量 imgUrl这样 <img>仅在 imgUrl 时显示已定义且不为空(即,当 this.myimage 是有效的 URL 字符串时)。我们还替换了 v-bind:src 的值与 imgUrl ,因为它已经包含完整的预期 URL 和 /home.jpg附:

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

updated jsFiddle

关于javascript - 将正则表达式添加到 Vue.js 数据对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50996407/

相关文章:

regex - 如何在后续计算中使用数组公式的输出?

html - 由于 div 的高度,页面没有从顶部开始

javascript - IE 版本 10.0.9200 "forgets"CSS 样式

javascript - 如何在 Javascript 中存储字节数组

javascript - Shopify 在感谢页面上访问带有其 ID 的产品,而无需在 url 中使用 '/admin'

javascript - 用于在导入语句中查找关键字的正则表达式

javascript - 带有 jQ​​uery 文本框的对话框

c# - 正则表达式拆分

vue.js - 如何将哈巴狗与 Electron 战配合使用?

javascript - 在Quasar中使用嵌套对象创建表