2
data = 'numbersXXXtext';

or

data = 'XXXtext';


var get = data.split('XXX');
var sum = get[1];

I would like get always "text". If data equals numbersXXXtext, the code works fine, but if data is XXXtext then get[1] is undefinded.

Does anyone know how I can solve this?

9
  • Wouldn't it be get[0] since it is the first, and only, item in the array? Commented Jan 7, 2012 at 13:28
  • I've posted an answer, and @Matt has proposed a neater alternative in a comment, but in which browser do you get undefined? I tried in Chrome and IE and "XXXtest".split("XXX")[1] returns "test" Commented Jan 7, 2012 at 13:35
  • 1
    Also, never name a variable get. get has become sort of a keyword. Commented Jan 7, 2012 at 13:40
  • 1
    Just looked it up in ECMA Script definition (ECMA-262, June 2011). I'm pretty sure that it should return an array with 2 elements: "" and "text". It certainly does in Java, and I would be very surprised if this isn't the same in most programming environments. Commented Jan 7, 2012 at 13:56
  • 3
    Mark, could you please add the runtime information (e.g. browser + version & platform) to the quesion for future reference, this seems to be an implementation mistake in the runtime Commented Jan 7, 2012 at 14:00

4 Answers 4

6

If there is only one occurrence of XXX in the string, the bit you want will always be the last item in the array returned by split. You can use pop to get the last item of an array:

var a = "numbersXXXtext";
var b = "XXXtext";

console.log(a.split('XXX').pop()); // "text"
console.log(b.split('XXX').pop()); // "text"
Sign up to request clarification or add additional context in comments.

2 Comments

I guess it's important to note here that this will remove the last element from the array; not just retrieve it.
Indeed, though it's immaterial in my answer because the array returned from split is never stored. You're right, of course.
1

Try this:

var sum = get.length > 1 ? get[1] : get[0]

1 Comment

get[get.length -1] would be a (better?) alternative.
1

Strange, i just tried your code, and it's working. (http://writecodeonline.com/javascript/) Are you sure you are not missing something?

    data = 'numbersXXXtext';
   //data = 'XXXtext';
    var get = data.split('XXX');

    document.write(get[1]);
    document.write("</br>");
    document.write(get);
    document.write("</br>");

I didn't get undefined in neither of your strings

Comments

1

An alternative using substring:

var data = 'numbersXXXtext';
var value = data.substring(data.indexOf('XXX') + 'XXX'.length);

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.