从字符串中删除字符串

我试图在 jQuery 中从一个字符串中删除一个字符串。

这是字符串:

username1, username2 and username3 like this post.

我想从这个列表中删除 username1,。 我尝试使用 .split(', ')将列表添加到一个数组中,但是我得到了一个错误。我假设这个错误是因为不是每个单词后面都有逗号。

我总是想从列表中删除第一项。username1只是一个示例用户名。如果当前登录用户喜欢这篇文章,第一个条目将始终是他们的用户名。

我试过了:

  var updated_list = $('#post_like_list').html().replace('username1, ', '');
$('#post_like_list').html(updated_list);

但这并没有更新名单。当使用 .text()而不是 .html()时,它确实更新了列表,但是我在列表中有链接,我需要保留它。

254094 次浏览

pretty sure you just want the plain old replace function. use like this:

myString.replace('username1','');

i suppose if you want to remove the trailing comma do this instead:

myString.replace('username1,','');

edit:

here is your site specific code:

jQuery("#post_like_list-510").text().replace(...)

If you just want to remove "username1" you can use a simple replace.

name.replace("username1,", "")

or you could use split like you mentioned.

var name = "username1, username2 and username3 like this post.".split(",")[1];
$("h1").text(name);

jsfiddle example

I assume that the text "username1" is just a placeholder for what will eventually be an actual username. Assuming that,

  • If the username is not allowed to have spaces, then just search for everything before the first space or comma (thus finding both "u1 likes this" and "u1, u2, and u3 like this").
  • If it is allowed to have a space, it would probably be easier to wrap each username in it's own span tag server-side, before sending it to the client, and then just working with the span tags.

To add on nathan gonzalez answer, please note you need to assign the replaced object after calling replace function since it is not a mutator function:

myString = myString.replace('username1','');

Pretty sure nobody answer your question to your exact terms, you want it for dynamic text

var newString = myString.substring( myString.indexOf( "," ) +1, myString.length );

It takes a substring from the first comma, to the end

This is how I coded for removing backslash using jQuery.

// Remove backslash from menu
let selector = jQuery('.crm-submenu-manage-invoices a');


// Get html
let stringRemove = selector.html();


// Remove backslash
stringRemove = stringRemove.replace('\\', '');


// Push back to selector
selector.html(stringRemove);

Adding to Shuvo's answer ... I needed to remove the title from an excerpt and used the following:

a.title is the text I wanted removed.
span.excerpt is where I wanted it removed FROM

var title=$('a.title').text();
let selector = jQuery('span.excerpt');
let stringRemove = selector.html();
stringRemove = stringRemove.replace(title, '');
selector.html(stringRemove);