pourmesomecode
pourmesomecode

Reputation: 4318

Splitting a String at a certain point/character in jQuery

I've seen this question asked a few times but i'm getting back some weird results.

Does split() in javascript convert a string into an array?

Basically, onClick I console.log - $(this).attr('class')

I get the classes from my element which is styled_main selected_origin. I want to append the second class to another element so I do this : $(this).attr('class').split("styled_main ")

However, I get back an array that looks like ["", "selected_origin"] I'm trying to get back just the string of which should look like : selected_origin

Upvotes: 1

Views: 592

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You could split your string by space and it will return ["styled_main", "selected_origin"] then get the second column (index 1) like :

$(this).attr('class').split(" ")[1];
//OR
$(this).attr('class').split(/\s+/)[1];

Hope this helps.


alert( "styled_main selected_origin".split(/\s+/)[1] );

Upvotes: 3

A. Wolff
A. Wolff

Reputation: 74420

You could use instead:

this.classList[1]

See support for classList

Upvotes: 4

Related Questions