-2

I wanted to split a string and get the string in two parts.

for example:

www.medicoshere.com/register.html?23457cedlske234cd

i wish to split the string in the above url and store the string that is after the ? to a variable. How can i do that.

3
  • 2
    Possible duplicate of How to split a string with angularJS Commented Sep 2, 2016 at 6:55
  • oops sorry......! But that is using filter i need it in controller Commented Sep 2, 2016 at 6:56
  • there are so many answers available. Commented Sep 2, 2016 at 6:59

5 Answers 5

2
var str = "www.medicoshere.com/register.html?23457cedlske234cd";
var res = str.split("?");
var value = res.slice(-1).pop(); // it will give 23457cedlske234cd
Sign up to request clarification or add additional context in comments.

6 Comments

Perfectly short and simple.
@NivasDhina Mine is shorter ;)
Thanks @NivasDhina
@Chrillewoodz but in your case if string may like www.medicoshere.com?register.html?23457cedlske234cd then OP need to read index 2 then. Am I right ? It's just an example my concern was if there might be 2 ? then indexing will differ.
True, but why would you have two ?? Then it would be ? followed by additional parameters as &.
|
2

Do this:

var newString = 'www.medicoshere.com/register.html?23457cedlske234cd'.split('?')[1]

Comments

0

You can get the part of the string you want in different ways

Using indexOf and substring

var str = "www.medicoshere.com/register.html?23457cedlske234cd";
var partIndex = str.indexOf("?");
var part = str.substring(partIndex + 1); // 23457cedlske234cd

Using Split

var part = str.split("?")[1];

The only problem is that, if you use substring, part will contain the whole string if the part you tried finding is not part of the string, say

var str = "www.medicoshere.com/register.html#23457cedlske234cd";
var partIndex = str.indexOf("?");
var part = str.substring(partIndex + 1); // www.medicoshere.com/register.html#23457cedlske234cd

while using split would return undefined as the value of part.

Comments

0

Try:-

$scope.string = "www.medicoshere.com/register.html?23457cedlske234cd";
$scope.s = $scope.string.split("?")

console.log(s[1] );

4 Comments

This will give the wrong string.
@Chrillewoodz then how it should be ?
1 instead of a 0.
@Chrillewoodz ok.! right.
0

Use .split to go from strings to an array of the split substrings:

var s = "one, two, three, four, five"
s.split(", ");  // ["one", "two", "three", "four", "five"]

You can then access the individual parts with s[0] etc.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.