【问题标题】:How to remove part of a string using jquery? [closed]如何使用 jquery 删除部分字符串? [关闭]
【发布时间】:2017-06-26 03:18:13
【问题描述】:

我需要以这种方式使用 jQuery 删除部分字符串:

我有这个字符串:

url(http://example.com/wp-content/uploads/2017/01/11_CAT_CONILLS_-w900-h600-150x150.jpg)

删除最后一个“/”之前的所有内容(这部分可以取其他值):

url(http://example.com/wp-content/uploads/2017/01/

删除:

)

离开:

11_CAT_CONILLS_-w900-h600-150x150.jpg

【问题讨论】:

  • 为什么选择 jQuery?你试过什么?
  • 我的问题与stackoverflow.com/questions/14202175/… 类似,并没有看到任何反对意见。
  • 那是因为几年前 SO 对那些没有努力或代码尝试解决手头问题的问题更加宽容

标签: jquery string replace


【解决方案1】:

我会混合使用IndexOfsubstring。它获取您想要保留和删除的所有 var 的长度。然后只需替换最后一个或使用其他方法删除最后一个字符。

var str = "url(http://example.com/wp-content/uploads/2017/01/11_CAT_CONILLS_-w900-h600-150x150.jpg)";

var returnstr = str.substring(str.lastIndexOf("/") + 1)

returnstr = returnstr.substring(-returnstr.length, returnstr.lastIndexOf(")"))

console.log(returnstr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

  • 对不起,但不是我需要的。要离开的字符串部分:'11_CAT_CONILLS_-w900-h600-150x150.jpg' 和要删除的部分:'url(example.com/wp-content/uploads/2017/01' 可以采用其他值。
  • 规则是删除最后一个“/”和最后一个“)”之前的所有内容。
  • 所以你想删除最后一个“/”和最后一个“)”之间的所有内容?
  • 不,我需要删除最后一个“/”之前的所有内容
  • 然后是最后一个“)”。
【解决方案2】:

您可以使用以下来获取所需的字符串

var str = "url(http://example.com/wp-content/uploads/2017/01/11_CAT_CONILLS_-w900-h600-150x150.jpg)";

alert(str.substring(str.lastIndexOf('/') + 1).replace(')', ''));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    • 2023-01-03
    • 2018-07-18
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多