How do I replace only the first occurence of a string?

0 favourites
  • 6 posts
From the Asset Store
This collection of music is the beautiful performance of rather small strings ensemble (8 first violins, 6 second violin
  • I want to replace a word by another one in a long text. I can use the "replace" system expression but it replace all occurence of my string in the whole text.

    Someone here know a trick to replace only the first occurence?

    Thanks in advance!

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • It's a bit long but you can use text.find("txt_to_replace") to find the index of the 1st occurence, then use left() and right() to build the new string with the replaced word.

    example : if you want to replace "txt" by "text" in a random string called "string":

    string = left(string , string.find("txt") & "text" & right(string, len(string)-string.find("txt")-3)

  • try Regex....

    RegexReplaceFirstWord.capx

  • Thanks for the reply guys!

    @korbaach: That's exactly what I need! I read about regexreplace and didn't understand exactly how to use it by reading the manual. You capx will help me a lot! Thanks for taking the time to do it!

  • Just to add to my previous reply, the documentation for the regexreplace says:

    RegexReplace(String, Regex, Flags, Replace)

    In String substitute matches for the regular expression Regex (with Flags) with the string Replace. The replacement string can contain the following special characters: $$ (inserts a $), $& (inserts the matched substring), $` (inserts the portion of the string that precedes the matched substring), or $' (inserts the portion of the string that follows the matched substring).

    ...but it didn't explain what exactly is regex and what is the flag. I suppose that this is coming from another langage so I'll google it...in your example korbaach you use "m" as a flag and I can reproduce it but I like to know what every thing in my code means.

    Thanks again!

  • Isn't this covered in the RegEx Documentation on W3Schools site?

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)