首页 > 解决方案 > 获取数据键值并包含在 .html 之前的 URL 中

问题描述

使用下面的代码从数据键中获取值并与 .html 连接。

初始网址将是 - http://www.test.com/en/location/london.html

基于收集的键值(例如:258888)需要附加在 URL 中,例如http://www.test.com/en/location/london.258888.html

但是,如果用户选择下一个选项值,现在它会获取最新的 URL 并包括新的密钥。在每个选择值上,它都包含到 URL。

喜欢 - http://www.test.com/en/location/london.258888.3899091.html

但是,它必须是唯一的。

http://www.test.com/en/location/london.3899091.html

$('a.dropdown-item').on('click', function(){
	let getDataKey = $(this).attr('data-key');
	let getWindowLocation = window.location.href;
	let getLocationVal = getWindowLocation.replace(/\.html/, '.' + getDataKey + '.html');
	window.location.replace(getLocationVal); 
});

标签: javascript

解决方案


[.0-9] 您还可以在正则表达式中包含可选的数字匹配器。

[0-9]字符范围 0-9
*零个或多个前面的字符。

代码示例:

$('a.dropdown-item').on('click', function(){
    let getDataKey = $(this).attr('data-key');
    let getWindowLocation = window.location.href;
    let getLocationVal = getWindowLocation.replace(/[.0-9]*\.html/, '.' + getDataKey + '.html');
    window.location.replace(getLocationVal); 
});

演示:

let string1 = "http://www.test.com/en/location/london.html";
let string2 = "http://www.test.com/en/location/london.3899091.html";
console.log("String1 : " + string1.replace(/[.0-9]*\.html/, '.' + "454545.html"));
console.log("String2 : " + string2.replace(/[.0-9]*\.html/, '.' + "258888.html"));


推荐阅读