1

I'm trying to get the last word from the string:

var str =  "Member/GetRefills";
var param = str.split(" ").pop();
console.log(param);

Expected result:

GetRefills
12
  • 3
    Try splitting on "/" instead. Commented Sep 19, 2019 at 17:23
  • well what do you expect when you split on a whitespace??? Commented Sep 19, 2019 at 17:27
  • And pop() removes the last entry from an array. So if you split on '/' and then pop() you will actually get "Member" and not "GetRefills". Commented Sep 19, 2019 at 17:29
  • 4
    @NawedKhan stick the following in your browser console. That is not correct. "Member/GetRefills".split('/').pop() Commented Sep 19, 2019 at 17:31
  • I haven't downvoted, though the avoidance of pop in favor of effectively writing what pop does, is odd. Commented Sep 19, 2019 at 17:38

2 Answers 2

7

Try splitting on "/" instead.

const str = "Member/GetRefills";
const param = str.split("/").pop();
Sign up to request clarification or add additional context in comments.

3 Comments

pop() removes the last entry from an array. So you will actually get "Member" and not "GetRefills"
@NawedKhan nope.
I take that back. "The pop() method removes the last element from an array and returns that element" so if you read the returned value it will be "GetRefills". However if you read the array now it will be one element less (not the case here, so never mind)
0

Do this instead:

var param = str.split('/');
var paramLast = param[param.length - 1];

pop() is not always a good practice. pop() removes the last element of an array which in some cases might cause problems.

param[param.length - 1] does the same job as pop() but more safely.

2 Comments

This assumes a single slash, which works in this specific case but would fail for 'Member/Bob/GerRefills'. Hence pop instead of [1].
I was actually updating the answer

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.