gpt4 book ai didi

javascript - 如何将 domain.com/foo/bar/baz/转换为类似 'foo bar baz' 的字符串?

转载 作者:行者123 更新时间:2023-11-30 09:01:05 24 4
gpt4 key购买 nike

基本上我希望能够获取 url 的结尾,并将其转换为字符串以在某处使用。

目前我正在这样做(这不是最佳选择):

// grab the path, replace all the forward slashes with spaces
local_path = location.pathname.toString().replace(/\//g,' ');

// strip empty spaces from beginning / end of string
local_path.replace(/^\s+|\s+$/g,""));

但我认为可能有更好的方法。帮忙?

编辑:我可以自信地摆脱那里的 .toString 方法吗?

最佳答案

如果你想避免使用正则表达式,你可以这样做:

location.pathname.substring(1).split('/').join(' ')

这将去掉开头的斜杠,但不会处理结尾的斜杠。如果您需要处理这些,您可以省略 substring 并使用 trim 进行现代实现或正则表达式:

location.pathname.split('/').join(' ').replace(/^\s+|\s+$/g, '')

关于javascript - 如何将 domain.com/foo/bar/baz/转换为类似 'foo bar baz' 的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9263946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com