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?
-
2You are trying to split the array..hence the errorSandeep Nayak– Sandeep Nayak2016年06月01日 14:38:19 +00:00Commented Jun 1, 2016 at 14:38
-
Could you tell me (which part of the code have i to change???)Sangamesh Davey– Sangamesh Davey2016年06月01日 14:39:20 +00:00Commented 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.ndugger– ndugger2016年06月01日 15:13:10 +00:00Commented Jun 1, 2016 at 15:13
3 Answers 3
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>
Comments
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
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.