Search code examples
powerbipowerquerym

How to conditionally transform text in a column in power query?


I am building a workbook in PowerBI and I have the need for doing a conditional appending of text to column A if it meets a certain criteria. Specifically, if column A does not end with ".html" then I want to append the text ".html" to the column.

A sample of the data would look like this:

URL                 | Visits
site.com/page1.html | 5
site.com/page2.html | 12
site.com/page3      | 15
site.com/page4.html | 8

where the desired output would look like this:

URL                 | Visits
site.com/page1.html | 5
site.com/page2.html | 12
site.com/page3.html | 15
site.com/page4.html | 8

I have tried using the code:

   #"CurrentLine" = Table.TransformColumns(#"PreviousLine", {{"URL", each if Text.EndsWith([URL],".html") = false then _ & ".html" else "URL", type text}})

But that returns an error "cannot apply field access to the type Text".

I can achieve the desired output in a very roundabout way if I use an AddColumn to store the criteria value, and then another AddColumn to store the new appended value, but this seems like an extremely overkill way to approach doing a single transformation to a column. (I am specifically looking to avoid this as I have about 10 or so transformations and don't want to have so many columns to add and cleanup if there is a more succinct way of coding)


Solution

  • You don't want [URL] inside Text.EndWith. Try this:

    = Table.TransformColumns(#"PreviousLine",
          {{"URL", each if Text.EndsWith(_, ".html") then _ else _ & ".html", type text}}
      )