0 votes
by (130 points)

Hello!

Is it somehow possible to "erase" or cut off some specific part of a variable string?

I was already trying to do it with (replace: ) combined with (substring:) commands, although it results in replacing all of the given characters in the previous sentence.

As in the example:

I'd like to cut last two characters in the phrase "ACBC BC AACAC", that's a result of a string shuffles.

As far as I understand the combination of commands recognizes the last two characters are "AC" and it will eventually slice out not only the last one, but also the rest as well turning the variable string to "BC BC A", what's not my intention. My intention was "ACBC BC AAC".

I'm much thankful for your response!

1 Answer

+1 vote
by (158k points)

You will need to use the JavaScript <String>.slice() function to extract a copy of the section of the string you want.

(set: $result to (string: $string.slice(0, $string's length - 2)))

NOTES:

1. While Harlowe uses a one-based index to reference the first character of a String value, JavaScript based strings are zero-based which means the first character has an index of 0 (zero).

2. Harlowe uses a special custom VarRef object to store any value assigned to a Story Variable, and unfortunately this special object doesn't play well with most JavaScript functions used directly within a (set:) macro assignment.
eg. the following example results in a "VarRef.create(...).slice is not a function" error message.

(set: $result to $string.slice(0, $string's length - 2))

In this specific use-case you can use the (string:) macro to overcome the limitation of the VarRef object.

Welcome to Twine Q&A, where you can ask questions and receive answers from other members of the community.

You can also find hints and information on Twine on the official wiki and the old forums archive.

See a spam question? Flag it instead of downvoting. A question flagged enough times will automatically be hidden while moderators review it.
...