1

I have an array. Within it I have 2 names. I want to pick only the surname by a split function, but it is not working. I have separated first name and last name using an underscore.

function spt (){
    var m= new Array('jitender_chand','shashi_cant')

    var j= m.split('_');

    document.getElementById('add').innerHTML=j;

    }
<body>
<input type="text" value="hii" id="jitender" />
<input type="button" onclick="spt()" />

<div id="add" ></div>

4 Answers 4

3

Please look into the following code.Hope this helps you:

HTML CODE:

<input type="text" value="hii" id="jitender" />
<input type="button" value="Click me to split" onclick="spt()" />
<div id="add" ></div> 

JS CODE:

function spt (){
    var m= new Array('jitender_chand','shashi_cant');
    for(var i=0;i<m.length;i++){
    var j= m[i].split('_')[1];       
    document.getElementById('add').innerHTML=
        document.getElementById('add').innerHTML + "," + j;
    }   
}  

Working Demo:

http://jsfiddle.net/C8h9K/

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

Comments

3

Should be:


var m = new Array('jitender_chand','shashi_cant')
var splitted = m[0].split("_")[1]; //for jitender_chand
//and use m[1].split("_")[1]; //for other name
alert(splitted);
document.getElementById('add').innerHTML=splitted;

OR if you want ta add surnames in an array, then:


var m = new Array('jitender_chand','shashi_cant');
var surname = [];
for(var s = 0; s < m.length; s++) {
  surname.push(m[s].split("_")[1]);
}
console.log(surname);
//if you want to join surnames, then
var joinedSurnames = surname.join(",");

Hope it helps

2 Comments

This. split is a method of the String class, not the Array class. ( developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… for more information )
its working but i want add last name of names in one click how does we do that
1

Yes but you can't call split on an array.

var j = new Array()
for (var i in m) {
    j.push(m[i].split('_'))
}

Comments

0

If you're using JavaScript 1.6 or later, you can use Array's map function to iterate over each member of the array and split the member (String) on underscore:

var m = ["jitender_chand", "shashi_cant"];
var j = m.map(function (name){
  return name.split("_")[1];
});

document.getElementById('add').innerHTML = j;

Comments

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.