15

my code

  var str =$(this).attr('id');

this will give me value == myid 5

   var str1 = myid
   var str2 = 5

i want something like this ..

how to achieve this using split method

2
  • 8
    As a side-note: I don't think id values should contain spaces. Commented Sep 5, 2012 at 10:07
  • 2
    As a side-note: To get ID from this element you may simply use this.id. Commented Sep 5, 2012 at 10:18

4 Answers 4

55
var str =$(this).attr('id');
var ret = str.split(" ");
var str1 = ret[0];
var str2 = ret[1];
Sign up to request clarification or add additional context in comments.

Comments

2

Use in-built function: split()

var source = 'myid 5';

//reduce multiple places to single space and then split
var splittedSource = source.replace(/\s{2,}/g, ' ').split(' ');

console.log(splittedSource);

​ Note: this works even there is multiple spaces between the string groups

Fiddle: http://jsfiddle.net/QNSyr/6/

Comments

1

One line solution:

//<div id="mypost-5">
var postId = this.id.split('mypost-')[1] ); //better solution than the below one!

-OR-

//<div id="mypost-5">
var postId = $(this).attr('id').split('mypost-')[1];

Comments

0

If there is one or more spaces between,

var str = $(this).attr('id');
var array = str.split(/\s+/g);
var str1 = array[0];
var str2 = array[1];

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.