当前位置: 代码迷 >> JavaScript >> 使用正则表达式替换字符串中的子字符串
  详细解决方案

使用正则表达式替换字符串中的子字符串

热度:86   发布时间:2023-06-13 11:54:01.0

我需要替换字符串中的子字符串。

字符串是 /string/otherstring?query=d78f1dbee59de41245fbf3c82b72b859ab688e30

子字符串 query=d78f1dbee59de41245fbf3c82b72b859ab688e30我需要替换为query=

我想使用regexp替换它,然后使用string.replace替换它。 但是我不能写正则表达式。

/\/string\/otherstring?query=/.exec(
    '/string/otherstring?query=d78f1dbee59de41245fbf3c82b72b859ab688e30'
)

没用

PS d78f1dbee59de41245fbf3c82b72b859ab688e30是sha1哈希

使用string.replace 您不需要应用exec函数。

string.replace(/(\/string\/otherstring\?query=)[A-Za-z0-9]+/g, "$1")

要么

如果您只想处理小写字母和数字,请尝试此操作。

string.replace(/(\/string\/otherstring\?query=)[a-z\d]+/g, "$1")

你可以在js中这样使用

'/string/otherstring?query=d78f1dbee59de41245fbf3c82b72b859ab688e30'.replace(/.*query=/,'')

要么

'/string/otherstring?query=d78f1dbee59de41245fbf3c82b72b859ab688e30'.replace(/\/string\/otherstring\?query=/,'')