179

If I have a string Abc: Lorem ipsum sit amet, how can I use JavaScript/jQuery to remove the string before the : including the :. For example the above string will become: Lorem ipsum sit amet.

1
  • 3
    I added the javascript tag since it's in the question and more relevant to the question than jquery.
    – Spudley
    Nov 3, 2010 at 22:57

2 Answers 2

410

There is no need for jQuery here, regular JavaScript will do:

var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);

Or, the .split() and .pop() version:

var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();

Or, the regex version (several variants of this):

var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];
5
  • 33
    Note if there is more than one : in the string, the second variant will return the string following the last one rather than the first as in the others. It is unfortunate that there is no split-only-n-times option in JS's split() method, which would allow you to do a Python-style .split(':', 1)[1]. (There is an optional number argument, but it doesn't do what any reasonable person would expect.)
    – bobince
    Nov 3, 2010 at 22:57
  • 2
    @bobince - You're right, I'm making a bit of an assumption here that he has a consistent label: something format, if that's not the case I'd go with the first option. Nov 3, 2010 at 22:58
  • 2
    You can split and join to drop some elements based on separator. "Abc:Lorem_ipsum_sit_amet".split(':').slice(1).join('.'); Mar 24, 2019 at 20:46
  • Hi, in jQuery I have this variable which I'd like to remove everything that comes after the character "|". I have been able to target the string by using this: var str = $('.order-product-list.align-left.box-content.any-1-1 > ul > li:nth-child(1) > div > dl.align-left > dd:nth-child(8)'); How do I do this? What comes after that character is dynamic and depends on the user on the web page. I want to hide/remove the last part after |
    – R. Srour
    Sep 1, 2021 at 8:17
  • as mentioned in the comment by @AmriteshAnand if there are more than one : you will need to do this: (join should use the same delimiter used in split() var str = "Abc: Lorem ipsum :sit: amet"; str = str.split(":").slice(1).join(":")
    – gmansour
    Sep 14, 2023 at 23:38
13

As a follow up to Nick's answer If your string contains multiple occurrences of : and you wish to only remove the substring before the first occurrence, then this is the method:

var str = "Abc:Lorem:ipsum:sit:amet";
arr = str.split(":");
arr.shift();
str = arr.join(":");
// str = "Lorem:ipsum:sit:amet"
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.