Ankur
Ankur

Reputation: 53

How to remove last word from a string

I have a text field in flash which contains the following string:

txtFld.text = " Mr. Suresh Kumar has written this article"

Now, what I want to do is, I want to remove the last word out of this and look like:

txtFld.text = " Mr. Suresh Kumar has written this"

Please Help, Thanks

Upvotes: 1

Views: 664

Answers (2)

Marty
Marty

Reputation: 39458

You can use a combination of .slice() and .lastIndexOf():

var base:String = "Mr. Suresh Kumar has written this article";

// Slice up until the last whitespace character.
var trunc:String = base.slice(0, base.lastIndexOf(" "));
trace(trunc);

Because AS2 does not have regex support, you should make sure the input is trimmed beforehand (whitespace removed from the front and end).

Upvotes: 2

Ivan Chernykh
Ivan Chernykh

Reputation: 42166

Try this:

    var text = txtFld.text;   // Saving text field' value in temporary variable
    text = text.split(" ");   // Splitting it at space delimiter
    text.splice(text.length-1 , 1); // Throwing out the last word
    txtFld.text = text.join(" ");   // Concatenating whole thing back

Upvotes: 2

Related Questions