Home > Net >  How to remove specific letters from a selected textfield value in flutter
How to remove specific letters from a selected textfield value in flutter

Time:05-03

So i have this textfield which has a controller and I am able to get the selected value that is been highlighted and change it without any issue.

CustomTextField(
  hintText: "Write something...",
  maxLines: null,
  controller: _controller,
  addBorder: false,
),

//Lets say the text inside the textfield is "Good morning my friends"

CustomButton(
    text: "Change",
    onClick: () {
      //This is to get the highlighted/selected text inside the textfield (Lets say it's "morning")
      String highlightedText = _controller.selection.textInside(_controller.text);

      //This is to get all the text before the highlighted text = "Good "
      String textBefore = _controller.selection.textBefore(_controller.text);

      //This is to get all the text after the highlighted text = " my friends"
      String textAfter = _controller.selection.textAfter(_controller.text);

      //This is to change or modify the highlighted text = "**morning**"
      String changeSelectedText = "**$selectedText**";

      //This is to join the before and after text and add to back to the controller = "Good **morning** my friends"
      String newText = textBefore   changeSelectedText   textAfter;
      
      print(newText);
      _controller.text = newText;
      
    }),

Now my problem is how do i first check if "morning" is already surrounded by "**morning**". Cause i used this

if (textAfter.contains("**") || textBefore.contains("**")) {
   textAfter = textAfter.replaceAll("**", "");
   textBefore = textBefore.replaceAll("**", "");
}

But it will check if every word in the textfield has ** not the word i selected. So please how do i do this maybe something like a regex or using it positions

CodePudding user response:

Use endsWith and startsWith instead:

if (textAfter.startsWith("**") || textBefore.endsWith("**")) {
  // Don't replace all ** with empty text, just make a substring and cut them off
  // textAfter = textAfter.replaceAll("**", "");
  // textBefore = textBefore.replaceAll("**", "");

  textAfter = textAfter.substring(2);
  textBefore = textBefore.replaceAll(0, textBefore.length - 2);
}
  • Related