Replace date from url

javascript

54 观看

3回复

1 作者的声誉

I would like to write a javascript function that replace a date in the format YYYY/MM/DD from an url to a specific string.

var url = "http://localhost/reussitemlm/2015/09/08/comment-vous-eviter-de-perdre-votre-attractivite-aux-yeux-de-vos-prospects/";

var newUrl = replaceDate(url, 'qtvideo');

console.log(newUrl);
"http://localhost/reussitemlm/qtvideo/comment-vous-eviter-de-perdre-votre-attractivite-aux-yeux-de-vos-prospects/"
作者: Koto de Mada 的来源 发布者: 2017 年 12 月 27 日

回应 3


0

6024 作者的声誉

决定

You can simply use a RegEx(d for digit) that searches for the expression dddd/dd/dd

let url = "http://localhost/reussitemlm/2015/09/08/comment-vous-eviter-de-perdre-votre-attractivite-aux-yeux-de-vos-prospects/",
date_format = /\d{4}\/\d{2}\/\d{2}/;

url = url.replace(date_format, "qtvideo");
console.log(url);

作者: zfrisch 发布者: 2017 年 12 月 27 日

0

2651 作者的声誉

This is rather rudimentary and I'm sure that regex experts have better patterns but the following expression should match

/[0-9]{4}\/[0-9]{2}\/[0-9]{2}/

Use it like this

var url = "http://localhost/reussitemlm/2015/09/08/comment-vous-eviter-de-perdre-votre-attractivite-aux-yeux-de-vos-prospects/";

url.replace(/[0-9]{4}\/[0-9]{2}\/[0-9]{2}/, 'qtvideo');
作者: richbai90 发布者: 2017 年 12 月 27 日

-1

6 作者的声誉

function replaceDate(url,str){
       let regex = /\d{4}[\/.]\d{1,2}[\/.]\d{1,2}/;
       let res = url.replace(regex.exec(url)[0], str);
       return res;

}

This should work for you ... thanks

作者: Nayeem Ur Rehman 发布者: 2017 年 12 月 27 日
32x32