187

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. Commented Nov 3, 2010 at 22:57

2 Answers 2

417

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];
Sign up to request clarification or add additional context in comments.

5 Comments

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 - 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.
You can split and join to drop some elements based on separator. "Abc:Lorem_ipsum_sit_amet".split(':').slice(1).join('.');
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 |
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(":")
14

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"

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.