0

This seems like it should be a very easy thing to do but I cannot seem to find it anywhere.

How can I use Javascript split() to split the string after a certain word that starts with say abcd.... so if I have "abcdHello one two three" , I would get " one two three". I am assuming that the abcd.... word will be at the beginning of the string. Thanks!

var allClassesString = $('.'+ui.item.overRow).find('.span12').attr('class');
var truncClassesString = allClassesString.split('span^'); // or span* - neither one works.
8
  • 5
    jQuery has no split function. But JavaScript does. Please post the code you've tried. Commented Jun 12, 2013 at 14:33
  • 3
    Thanks. Fixed it. People seem to be on fire for an honest mistake. Commented Jun 12, 2013 at 14:35
  • @GeorgiAngelov Feel for you man--ignore the rude ones. Commented Jun 12, 2013 at 14:36
  • 3
    This seems to be more of a replace() than split() use-case. Commented Jun 12, 2013 at 14:37
  • Not really @DavidThomas . I was really interested in simply truncating my string by removing the abcd... I guess I could have replaced the abcd... word with "" but what Dogbert suggested first, worked perfectly. Commented Jun 12, 2013 at 14:45

1 Answer 1

5

If I understood correctly, you want this:

"abcdHello one two three".split(/^abcd\S*/)
=> ["", " one two three"]

RegExp explanation:

^    -> Start of string
abcd -> Match "abcd" literally
\S   -> Not a whitespace
*    -> Repeat "\S" as many times as possible.

After your comment on the question, if you just want to remove the matching text, use .replace as @DavidThomas suggested.

"abcdHello one two three".replace(/^abcd\S*/, '')
=> " one two three"

Add g modifier to the RegExp if you want to replace more than one occurance:

"abcdHello one two three".replace(/^abcd\S*/g, '')
" one two three"
Sign up to request clarification or add additional context in comments.

3 Comments

He wants to get one two three, might be worth joining the array back together with .join('').
@DavidThomas, OP said split, so not sure if he just wants to replace, or split a long string with that delimiter. Will wait for OP's reply first.
Yeah, it was a suggestion for expanding the answer, rather than replacing it is all.

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.