1

Im trying to get the character after my string, I am using the bellow code but it dose not seem to work.

Input value: fileinput-1

Expected result: 1

Any ideas. This is my code:

str = element.id;
str.substr(str.indexOf('-') + 1);
console.log(str);
index = str;  
2
  • @Beep: Could you clear up if it is only the very last character you want, or if it's any character after the hyphen? For example, if your input was fileinput-12, what output would you expect? Commented Sep 28, 2017 at 12:13
  • your answer was perfect thanks Commented Sep 28, 2017 at 12:32

3 Answers 3

2

The problem is that you are not doing anything with the result of the substr call. So the value of str is not being updated.

You need to assign the result back to str, like this:

str = str.substr(str.indexOf('-') + 1);
Sign up to request clarification or add additional context in comments.

4 Comments

As string in JavaScript are immutable, we need to assign return value from substr back to str.
The question is Get Last character of String in angular?? not get the all char's after the -.
@RameshRajendran: Is somebody in a grump? It wasn't me that downvoted your answer, even though I did comment... but I deleted the comment because I couldn't be bothered dealing with your reply
@Ram The title may say 'last character' but the question body says "get the character after my string"... also, the code suggests all characters after the hyphen. That means, 2 bits of information that indicate it should be characters after the hyphen, and only 1 bit of information it should be the last character. If you think all the way back to pre-school you will remember that 2 is greater than 1.... I appreciate that may have been a long time ago so I understand why you might be confused. Not to mention the OP accepted my answer
1

substr() returns a string, you should catch it like this:

str = str.substr(str.indexOf('-') + 1 , 1);

or

var newstr = str.substr(str.indexOf('-') + 1, 1);

3 Comments

The question is How to Get Last character of String in angular??. not get the all char's after the -.
@RameshRajendran you are right, I fixed it.
@RameshRajendran The question was changed. :-/
0

try this with substr() or slice() one.

var text = "field-1";
var result = text.substr(text.length - 1);
alert(result)
// or use slice
  var res= text.slice(-1); 
  alert(res)

1 Comment

Tempted to downvote because of ^^^^^^^ LOL (and missing semicolons) (and inconsistent indents) (and unnecessary second variable)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.