AX / D365FO – Removing white spaces in the middle of the string in X++

Do you need to remove spaces from a string in X++? For example:

str txt = " abc def ghi";

Suppose you want to remove the spaces between 'abc', 'def', and 'ghi' in the string txt. You can achieve this by using the strRem function in X++. Here’s how:

str txt = " abc def ghi";
str removedSpaces = strRem(txt, " ");

The strRem function removes all occurrences of a specified substring from a given string. In this case, it removes all spaces (" ") from the txt string.

After executing the code above, the removedSpaces variable will contain:

"abcdefghi"

This method is useful when you need to eliminate any spaces that might interfere with data processing or comparisons.

Alternative Method: Using Regular Expressions

If you need to remove all whitespace characters (including tabs, new lines, etc.), you can use regular expressions with the .NET Regex class:

using System.Text.RegularExpressions;

str txt = " abc def\tghi\n";
Regex regex = new Regex(@"\s+");
str removedSpaces = regex.Replace(txt, "");

n this example:

  • \s+ is a regex pattern that matches one or more whitespace characters.
  • regex.Replace(txt, "") replaces all matched whitespace with an empty string.

The removedSpaces variable will contain:

"abcdefghi"

Conclusion

Removing spaces from strings in X++ is straightforward with the strRem function or by utilizing regular expressions for more complex scenarios. Choose the method that best fits your needs.

Happy coding!

Leave a comment