Sangamesh Davey Sangamesh Davey - 4 months ago 6
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?


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.