JavaScript函数如何将URL提取的小写路径段转换为大写返回?
你可以直接对提取到的路径分段调用JavaScript内置的toUpperCase()方法,该方法会将字符串中所有小写字符转换为大写,不影响原有的大写字符、数字和特殊符号。
调整后的代码如下:
function() { var pageUrl = window.location.href; return pageUrl.split("/")[3].toUpperCase(); }
如果需要兼容URL路径层级不足3级、提取结果为undefined的场景,可以加一层判断避免调用方法时报错:
function() { var pageUrl = window.location.href; const targetSegment = pageUrl.split("/")[3]; return targetSegment ? targetSegment.toUpperCase() : ""; }
内容的提问来源于stack exchange,提问作者Mr. M
相关产品推荐
相关产品推荐

