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;  
musefan
  • 47,875
  • 21
  • 135
  • 185
Beep
  • 2,737
  • 7
  • 36
  • 85
  • @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? – musefan Sep 28 '17 at 12:13
  • your answer was perfect thanks – Beep Sep 28 '17 at 12:32

3 Answers3

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);
musefan
  • 47,875
  • 21
  • 135
  • 185
  • As string in JavaScript are immutable, we need to assign return value from `substr` back to `str`. – Rajeev Ranjan Sep 28 '17 at 11:47
  • The question is `Get Last character of String in angular??` not get the all char's after the `-`. – Ramesh Rajendran Sep 28 '17 at 11:53
  • 1
    @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 – musefan Sep 28 '17 at 11:59
  • @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 – musefan Sep 28 '17 at 12:09
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);
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)
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
  • Tempted to downvote because of ^^^^^^^ LOL (and missing semicolons) (and inconsistent indents) (and unnecessary second variable) – Alan Larimer Sep 28 '17 at 13:01