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.
-
3I added the javascript tag since it's in the question and more relevant to the question than jquery.Spudley– Spudley2010-11-03 22:57:04 +00:00Commented Nov 3, 2010 at 22:57
Add a comment
|
2 Answers
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 Comments
bobince
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.)Nick Craver
@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.Amritesh Anand
You can split and join to drop some elements based on separator.
"Abc:Lorem_ipsum_sit_amet".split(':').slice(1).join('.');R. Srour
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 |gmansour
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(":")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"