0

I would like to add value to my URL after the specific text. How I can achieve this?

I found a solution where I can slice and add values but I don't have the index fixed in this URL.

const url = 'www.website.com/api/test1/test2';

const url = 'www.website.test.com/api/test1/test2/test3';

const output1 = 'www.website.com/api/ha/test1/test2';

const output2 = 'www.website.test.com/api/ha/test1/test2/test3';
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Bravo
  • 61
  • 2
  • 7
  • 26
  • What is the "specific text"? You say you found a solution where you can slice and add values but don't show it. The index can be specified as the output of a function, so you don't need a fixed value. There are literally hundreds of questions about this on Stack Overflow. – Heretic Monkey Oct 13 '21 at 20:05
  • Does this answer your question? [How do I concatenate a string with a variable?](https://stackoverflow.com/questions/4234533/how-do-i-concatenate-a-string-with-a-variable) – Heretic Monkey Oct 13 '21 at 20:14
  • Or [How do I parse a URL into hostname and path in javascript?](https://stackoverflow.com/q/736513/215552) – Heretic Monkey Oct 13 '21 at 20:18

3 Answers3

0

If you want to add a certain value after a certain string you can simply replace the known value with the new string:

url.replace('/api', '/api/ha')
0

If you don't have a fixed index, you should use Regex to search the string. Could look like this:

/(www.\D+\/api\/)[\D\d\/]+/gm

This code would put the before and after into a group and you can then do

group1 + yourstring + group2

to add it together.

Michza
  • 39
  • 3
0

I prefer working with URL

const url1 = new URL('https://www.website.com/api/test1/test2');
const pn =  url1.pathname.split("/")
pn.splice(2,0,'ha')
url1.pathname=pn.join("/");
console.log(url1.href)
mplungjan
  • 169,008
  • 28
  • 173
  • 236