0

I have a url like "http://localhost:8080/myapp?age=12&add=mumbai&name=myname" Now I want to add one parameter(tel=12345) as the first parameter in the query string like "http://localhost:8080/myapp?tel=12345&age=12&add=mumbai&name=myname"

I have tried below snippet

var str = "http://localhost:8080/myapp?age=12&add=mumbai&name=myname";

var txt2 = str.slice(0, str.indexOf("?")) + "tel=12345&" + str.slice(str.indexOf("?"));
alert(txt2);

But the result is incorrect

http://localhost:8080/myapptel=12345&?age=12&add=mumbai&name=myname

Is there a better way???

2
  • 1
    why can't you use simple string concatenation? any particular reason behind this? Commented May 4, 2017 at 5:07
  • I have a requirement where I want to add it as a first parameter and not append it in the string Commented May 4, 2017 at 5:09

3 Answers 3

1

Try this:

var str = "http://localhost:8080/myapp?age=12&add=mumbai&name=myname";

var txt2 = str.slice(0, str.indexOf("?")) + "?" + "tel=12345&"
//                                        ^^^^^
    + str.slice(str.indexOf("?") + 1);
//                               ^^^

alert(txt2);

Sign up to request clarification or add additional context in comments.

2 Comments

It gives "localhost:8080/myapp?tel=12345&?age=12&add=mumbai&name=myname"
Yes, sorry. Edited.
0

You need to just increment index by 1 and this will work.

E.g.:

var txt2 = str.slice(0, str.indexOf("?") + 1 ) + "tel=12345&" + str.slice(str.indexOf("?") + 1);

Comments

0
var txt2=str.split('?')[0]+'?tel=12345&'+str.split('?')[1];

Just a variation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.