0

I have a piece of string

"res1"

I want the output to be:

1

What I have tried till now:

HTML:

<!DOCTYPE html>
<html>
    <body>
        <p id="demo"></p>
        <button type="button" onclick="myFunction()">Try</button>
    </body>
</html>

JavaScript:

function myFunction() {
    var str = "res1";
    var result = str.split("res");
    document.write(result);//returns ,1
    var mystring = result.split(',').join("");

    document.getElementById("demo").innerHTML = mystring;
}

The error which I receive is:

Uncaught TypeError: result.split is not a function

What am I missing?

3
  • 2
    You are trying to split the array..hence the error Commented Jun 1, 2016 at 14:38
  • Could you tell me (which part of the code have i to change???) Commented Jun 1, 2016 at 14:39
  • If all you're trying to do is get a number out of a string, you'd be better off with a regex. Commented Jun 1, 2016 at 15:13

3 Answers 3

2

You can simply do this:

 function myFunction() {
       var str = "res1";
       var result = str.split("res"); // output => ["","1"]
       //document.write(result);//returns ,1
       //var mystring = result.split(',').join("");

       document.getElementById("demo").innerHTML = result[1];
     }
<p id="demo"></p>
<button type="button" onclick="myFunction()">Try</button>

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

Comments

1

If you generally want to get the last character of the string you could use something like:

var str = "res1";
str.substr(str.length - 1)

3 Comments

Thanks for the effort
@SangameshDavey nice. then don't forget to set the answer to be the right one so others with the same problem can use it too. ^^
I am allowed to accept your answer right only after 4 mins..Will do it..Thanks again
1

The reason yours isn't working is because when you call .split() it returns an array, so when you call result.split(',') you're calling that on an array, which array's do not have this method, which is why you are getting your error. The other answers show an alternative, but I wanted to highlight why you are getting that error.

1 Comment

@BM0e872,,Thanks Understood my mistake and thanks for telling me

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.