简体   繁体   English

在jQuery中删除字符串中的最后8个字符

[英]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. 我从ajax调用中获得了一些输出数据,我想取出数据的最后8个字符,但还要从该字符串中删除它们,这样当我打印数据时,所取的字符串将不会显示出来。

Here is the code I have tried, It successfully takes that last 8 characters but does not remove them. 这是我尝试过的代码,它成功获取了最后8个字符,但没有将其删除。

var data = "This is some data 12345678";
var comment_id = data.slice(-8);
jQuery.trim(comment_id);
$('#comments_'+comment_id).html(data);
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的值,它只会从data取出最后8个字符。 data is a string and it is immutable data是一个字符串,并且是不可变的

add the following line after this line 在此行之后添加以下行

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

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) (我没有注意到您想要的,所以很抱歉)

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);

Return json from server side code 从服务器端代码返回json

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

You can access it like 您可以像访问它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM