Home > other >  Hwo to change dynamically the last two parameteres?
Hwo to change dynamically the last two parameteres?

Time:05-07

I have the followng string

https://picsum.photos/id/1025/4951/3301

I need to replace here the last two numbers 4951 and 3301 with 200 so at the end i will have https://picsum.photos/id/1025/200/200

How can i do this automatically ?

what i tried

i tried to split them by '/'

 const splittedUrl = image.download_url.split('/');
  splittedUrl[splittedUrl.length - 1] = '200';
splittedUrl[splittedUrl.length - 2] = '200';

but it is not possible because i have // after https

so when i join it i get wrong output at the end

  console.log(splittedUrl.join(' '));

CodePudding user response:

You are doing all good just instead join the string with empty string join with the /

const stringVal = 'https://picsum.photos/id/1025/4951/3301';
const stringSplited = stringVal.split('/');



stringSplited[stringSplited.length - 1] = '200';
stringSplited[stringSplited.length - 2] = '200';


const stringJoined = stringSplited.join('/') 

//this will log the following: https://picsum.photos/id/1025/200/200
console.log(stringJoined)

CodePudding user response:

A regular expression replacement is designed for this sort of work. A simple one which matches a / followed by some digits, followed by another /, some more digits, and the end of the string is /\/\d \/\d $/. We can write it like this:

const replaceLastTwos = (s1, s2) => (s) =>
  s .replace (/\/\d \/\d $/, `/${s1}/${s2}`)

const replaceLastTwoWith200s = replaceLastTwo (200, 200)

console .log (replaceLastTwoWith200 ('https://picsum.photos/id/1025/4951/3301'))

Of course if those 200s are really fixed, you can simplify this to:

const replaceLastTwoWith200s = (s) => s .replace (/\/\d \/\d $/, `/200/200`)
  • Related