Sangamesh Davey Sangamesh Davey - 2 months ago 10
Javascript Question

JavaScript split() function not working

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?

Answer

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)