another user
another user

Reputation: 93

Delete last 8 characters out of string in Jquery

I have some output data from an ajax call and I would like to take out the last 8 characters of the data but also delete them out of that string that when I print out the data, the string I have taken would not show up.

Here is the code I have tried, It successfully takes that last 8 characters but does not remove them.

var data = "This is some data 12345678";
var comment_id = data.slice(-8);
jQuery.trim(comment_id);
$('#comments_'+comment_id).html(data);

Upvotes: 0

Views: 4079

Answers (4)

user5066707
user5066707

Reputation:

Why not substring?

var strLen=data.length,
comment_id=data.substring((strLen>=8?strLen-8:0),strLen);

(ignore this part of my answer)

To remove them, do almost the same:

data=data.substring(0,strLen-8)

Equivalent of:

"daddaddad" to "d"

(I didn't note you was wanting that, so I'm sorry)

Upvotes: 1

Ankit vadariya
Ankit vadariya

Reputation: 1263

Return json from server side code

{message:"This is some data",comment_id:"12345678"}

You can access it like

$('#comments_'+data.comment_id).html(data.message);

Upvotes: 1

Josh Davenport-Smith
Josh Davenport-Smith

Reputation: 5511

Here's a nice approach using regex that's a bit cleaner too:

var data = "This is some data 12345678",
    comment_id = data.match(/\d{8}$/)[0];
data = data.replace(comment_id, '').trim();
$('#comments_' + comment_id).html(data);

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68393

var comment_id = data.slice(-8);

this line will not change the value of data it will only take out last 8 characters from the data. data is a string and it is immutable

add the following line after this line

data = data.substring(0, data.length -8);

Upvotes: 6

Related Questions