首页 > 解决方案 > 有没有办法删除两个斜杠内的所有字符?

问题描述

我正在尝试仅使用正则表达式来删除 '/please-remove-this/' 并将 '%20' 替换为 ' '。

let str = '/please-remove-this/Hello%20world'

let strNew = str.replace(/%20/g, ' ').substring(20)

strNew = 'Hello world'

'Hello world' 是正确的输出,但我觉得有一种更有效的方法可以只使用正则表达式

标签: javascriptregex

解决方案


而是替换%20您可以使用解码decodeURI

let str = '/please-remove-this/Hello%20world';
let out = decodeURI(str.replace(/\/.*\//g, ''));
console.log(out)
仅使用正则表达式

let str = '/please-remove-this/Hello%20world';
let out = decodeURI(str.replace(/\/.*\/(.*)%20(.*)/, '$1 $2'));
console.log(out)


推荐阅读