最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Remove text after a certain character with Javascript or JQuery - Stack Overflow

programmeradmin2浏览0评论

I am using an e-merce platform that renders the shopping cart as below inside a single div, and I would like to remove everything after the number of items in the cart, starting with the "," through to the end of "Cart".

The number of items and the Total could be any value, so I would need something that wouldn't rely upon a set variable. This would also have to work dynamically as items could be added to the cart after the page loads and would need to update accordingly.

As I am rather new to Javascript and JQuery, I would very much appreciate any help that includes the full script.

1 item(s), Total: $25.19 View Cart

I am using an e-merce platform that renders the shopping cart as below inside a single div, and I would like to remove everything after the number of items in the cart, starting with the "," through to the end of "Cart".

The number of items and the Total could be any value, so I would need something that wouldn't rely upon a set variable. This would also have to work dynamically as items could be added to the cart after the page loads and would need to update accordingly.

As I am rather new to Javascript and JQuery, I would very much appreciate any help that includes the full script.

1 item(s), Total: $25.19 View Cart

Share Improve this question asked Nov 26, 2012 at 21:07 EricEric 211 silver badge2 bronze badges 4
  • 1 var con = $("#cartelementid"); con.text(con.text().split(',')[0]); – Shmiddty Commented Nov 26, 2012 at 21:10
  • 1 there should be a return value containing number of items, you shouldnt have to make the split. Investigate the api for what you're using. – SpYk3HH Commented Nov 26, 2012 at 21:11
  • To avoid splitting you could always do THIS – adeneo Commented Nov 26, 2012 at 21:18
  • Possible duplicate, stackoverflow./q/5631384/425313 – Brad Koch Commented Apr 24, 2013 at 15:46
Add a ment  | 

2 Answers 2

Reset to default 6

Try

var text = "1 item(s), Total: $25.19 View Cart";
text = text.split(",")[0];

With a regex replace - /,.*/ will find a ma followed by any number of other characters:

var text = "1 item(s), Total: $25.19 View Cart";

text = text.replace(/,.*/, "");

"This would also have to work dynamically as items could be added to the cart after the page loads and would need to update accordingly."

Well then you'd need to call the above code from wherever new items are added.

发布评论

评论列表(0)

  1. 暂无评论