Sangamesh Davey Sangamesh Davey - 1 year ago 77
Javascript Question

Javscript split() function not working

I have a piece of string


I want the output to be:


What I have tried till now:


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


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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download