在jQuery中拆分URL路径并获得其中的一部分 [英] Splitting a URL path in jQuery and getting a part of it

查看:130
本文介绍了在jQuery中拆分URL路径并获得其中的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要拆分用户输入的路径并仅抓取其中的某些部分. 例如如果用户输入的路径为:

I need to split the path entered by the user and grab only certain part of it. For e.g. if the use enters path as:

/content/mypath/myfolder/about/images/abc.jpg

然后我只想显示images/abc.jpg.

我要

未捕获的错误:语法错误,无法识别的表达式

Uncaught Error: Syntax error, unrecognized expression

此刻的错误.

这是我的代码.

$(document).ready(function(){
  $('#getData').click(function(){
    imgPath = $('#imgPath').val();

    console.log($(imgPath).split('/'));

    //console.log(slicedPath);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
Image path: <input type="text" id="imgPath">
<button id="getData">Click</button>

推荐答案

$(imgPath)将尝试找到imgPath是选择器的元素.由于用户输入的路径不是正确的选择器,因此会引发错误. 例如,如果用户输入/content/mypath/myfolder/about/images/abc.jpg,则选择器将是$('/content/mypath/myfolder/about/images/abc.jpg'),这是无效的表达,因此会出现错误.

$(imgPath) will try to locate the element where imgPath is selector. As the Path entered by user is not correct selector, it'll throw error. Example, if user entered /content/mypath/myfolder/about/images/abc.jpg the selector will be $('/content/mypath/myfolder/about/images/abc.jpg') which is not valid express, thus the error.

您可以使用RegEx获取图像路径

You may use RegEx to get the image path

imgPath.match(/images\/.*$/i)[0]

正则表达式将匹配images/,后跟任意数量的字符. match返回一个数组,因此使用[0]将获得图像路径.

The regex will match images/ followed by any number of characters. match returns an array, so using [0] will get the image path.

$(document).ready(function() {
  $('#getData').click(function() {
    var imgPath = $('#imgPath').val();

    console.log(imgPath.match(/images\/.*$/i)[0]);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
Image path: <input type="text" id="imgPath" value="/content/mypath/myfolder/about/images/abc.jpg">
<button id="getData">Click</button>

这篇关于在jQuery中拆分URL路径并获得其中的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆