📝

Funciones de Texto (Text.*)

Manipula, limpia y transforma cadenas de texto con las funciones Text.* de Power Query M.

Principiante Intermedio
🔠

Mayúsculas y Minúsculas

Text.Upper

Principiante

Sintaxis

Text.Upper(text as nullable text, optional culture as nullable text) as nullable text

¿Qué hace?

Convierte todos los caracteres de un texto a mayúsculas. Puedes especificar una cultura para respetar reglas lingüísticas específicas.

Ejemplo

Text.Upper("kawaii power bi")
// Resultado: "KAWAII POWER BI"

Text.Upper("straße", "de-DE")
// Resultado: "STRASSE" (alemán: ß → SS)

Text.Lower

Principiante

Sintaxis

Text.Lower(text as nullable text, optional culture as nullable text) as nullable text

¿Qué hace?

Convierte todos los caracteres a minúsculas. Muy útil para normalizar campos antes de comparaciones o agrupaciones.

Ejemplo

Text.Lower("VENTAS Q1 Madrid")
// Resultado: "ventas q1 madrid"

Text.Proper

Principiante

Sintaxis

Text.Proper(text as nullable text, optional culture as nullable text) as nullable text

¿Qué hace?

Capitaliza la primera letra de cada palabra. Perfecto para normalizar nombres de personas o ciudades.

Ejemplo

Text.Proper("ana garcía martínez")
// Resultado: "Ana García Martínez"
💡 Tip kawaii: Text.Proper también capitaliza después de guiones y apóstrofes. Ideal para nombres compuestos como "María-José" o "O'Brien".
📏

Longitud y Limpieza

Text.Length

Principiante

Sintaxis

Text.Length(text as nullable text) as nullable number

¿Qué hace?

Devuelve el número de caracteres de un texto, incluyendo espacios. Útil para validaciones y cálculos de longitud.

Ejemplo

Text.Length("Power Query")
// Resultado: 11

// Filtrar códigos con longitud incorrecta
Table.SelectRows(tabla, each Text.Length([Codigo]) = 8)

Text.Trim

Principiante

Sintaxis

Text.Trim(text as nullable text, optional trim as any) as nullable text

¿Qué hace?

Elimina espacios en blanco (u otros caracteres) al inicio y al final de un texto. El parámetro trim puede ser un carácter específico a eliminar.

Ejemplo

Text.Trim("  hola mundo  ")
// Resultado: "hola mundo"

Text.Trim("***precio***", "*")
// Resultado: "precio"

Text.Clean

Intermedio

Sintaxis

Text.Clean(text as nullable text) as nullable text

¿Qué hace?

Elimina todos los caracteres no imprimibles de un texto (caracteres de control, tabuladores, saltos de línea, etc.). Muy útil al importar datos de sistemas legacy.

Ejemplo

Text.Clean("hola" & Character.FromNumber(9) & "mundo")
// Elimina el tabulador: "holamundo"

// En una columna
Table.TransformColumns(tabla, {{"Descripcion", Text.Clean}})
⚠️ Ojo con esto: Text.Clean elimina saltos de línea (#(lf), #(cr)). Si necesitas conservarlos, usa Text.Replace primero.
🔍

Búsqueda

Text.Contains

Principiante

Sintaxis

Text.Contains(text as nullable text, substring as text, optional comparer as nullable function) as nullable logical

¿Qué hace?

Devuelve true si el texto contiene la subcadena especificada. Por defecto es sensible a mayúsculas.

Parámetros

  • text — Texto donde buscar
  • substring — Subcadena a buscar
  • comparer — Comparador opcional (ej. Comparer.OrdinalIgnoreCase)

Ejemplo

Text.Contains("Kawaii Power BI", "Power")
// true

// Búsqueda sin distinción de mayúsculas
Text.Contains("Madrid Centro", "madrid", Comparer.OrdinalIgnoreCase)
// true

// Filtrar filas que contengan "ERROR"
Table.SelectRows(tabla, each Text.Contains([Mensaje], "ERROR"))

Text.StartsWith / Text.EndsWith

Principiante

Sintaxis

Text.StartsWith(text as nullable text, substring as text, optional comparer as nullable function) as nullable logical
Text.EndsWith(text as nullable text, substring as text, optional comparer as nullable function) as nullable logical

¿Qué hace?

Comprueba si un texto empieza o termina con una subcadena determinada. Muy útiles para filtrar por prefijos o sufijos.

Ejemplo

Text.StartsWith("ES-2024-001", "ES-")   // true
Text.EndsWith("informe_final.xlsx", ".xlsx")  // true

// Filtrar archivos Excel
Table.SelectRows(archivos, each Text.EndsWith([Name], ".xlsx"))

Text.PositionOf

Intermedio

Sintaxis

Text.PositionOf(text as text, substring as text, optional occurrence as nullable number, optional comparer as nullable function) as any

¿Qué hace?

Devuelve la posición (índice base 0) donde aparece la subcadena. Si no se encuentra, devuelve -1. Con Occurrence.All devuelve una lista de todas las posiciones.

Ejemplo

Text.PositionOf("hola mundo", "mundo")  // 5
Text.PositionOf("aabaa", "a", Occurrence.All)  // {0, 1, 3, 4}
Text.PositionOf("Power BI", "X")  // -1
✏️

Reemplazar

Text.Replace

Principiante

Sintaxis

Text.Replace(text as nullable text, old as text, new as text) as nullable text

¿Qué hace?

Reemplaza todas las ocurrencias de old por new en el texto. Es sensible a mayúsculas.

Ejemplo

Text.Replace("ventas,2024,madrid", ",", " | ")
// "ventas | 2024 | madrid"

// Eliminar caracteres no deseados
Text.Replace([Telefono], " ", "")  // quita espacios del teléfono
Text.Replace([Precio], "€", "")   // quita símbolo de euro

Text.Remove / Text.Select

Intermedio

Sintaxis

Text.Remove(text as nullable text, removeChars as any) as nullable text
Text.Select(text as nullable text, selectChars as any) as nullable text

¿Qué hace?

Text.Remove elimina todos los caracteres especificados. Text.Select conserva sólo los caracteres especificados. Aceptan un carácter o una lista.

Ejemplo

// Eliminar vocales
Text.Remove("hola mundo", {"a","e","i","o","u"})
// "hl mnd"

// Conservar sólo dígitos
Text.Select("Tel: +34 91 234 56 78", {"0".."9"})
// "34912345678"

// Conservar letras y números
Text.Select([Codigo], {"A".."Z","a".."z","0".."9"})
💡 Tip kawaii: Las ranges de caracteres {"0".."9"} y {"A".."Z"} son una sintaxis muy potente de M para definir conjuntos de caracteres de forma concisa.
✂️

Dividir y Combinar

Text.Split

Principiante

Sintaxis

Text.Split(text as text, separator as text) as list

¿Qué hace?

Divide un texto por el separador indicado y devuelve una lista de fragmentos. El equivalente M de TEXTOANTESDE/TEXTODESPUESDE de Excel pero más potente.

Ejemplo

Text.Split("Madrid;Barcelona;Valencia", ";")
// {"Madrid", "Barcelona", "Valencia"}

// Obtener el primer elemento tras dividir
List.First(Text.Split([Email], "@"))
// Devuelve el nombre de usuario del email

Text.Combine

Principiante

Sintaxis

Text.Combine(texts as list, optional separator as nullable text) as text

¿Qué hace?

Une una lista de textos, opcionalmente con un separador. Es el inverso de Text.Split.

Ejemplo

Text.Combine({"Nombre", "Apellido1", "Apellido2"}, " ")
// "Nombre Apellido1 Apellido2"

// Concatenar columnas con separador
Text.Combine({[Ciudad], [Pais]}, ", ")
// "Madrid, España"
🎯

Extraer Subcadenas

Text.Start / Text.End

Principiante

Sintaxis

Text.Start(text as nullable text, count as number) as nullable text
Text.End(text as nullable text, count as number) as nullable text

¿Qué hace?

Extrae los primeros (o últimos) count caracteres de un texto. Equivalentes a IZQUIERDA/DERECHA de Excel.

Ejemplo

Text.Start("ES-2024-001", 2)   // "ES"
Text.End("informe_2024.xlsx", 4)  // "xlsx"

// Extraer código de país de un identificador
Text.Start([CodigoProducto], 3)  // "ESP", "FRA", etc.

Text.Middle

Intermedio

Sintaxis

Text.Middle(text as nullable text, start as number, optional count as nullable number) as nullable text

¿Qué hace?

Extrae una subcadena desde la posición start (base 0) con longitud count. Si omites count, extrae hasta el final. Equivalente a EXTRAE de Excel.

Ejemplo

Text.Middle("ES-2024-001", 3, 4)   // "2024"
Text.Middle("ES-2024-001", 3)       // "2024-001"

// Extraer año de un código con formato "XX-YYYY-NNN"
Text.Middle([Codigo], 3, 4)

Text.BeforeDelimiter / Text.AfterDelimiter

Intermedio

Sintaxis

Text.BeforeDelimiter(text as nullable text, delimiter as text, optional index as any) as any
Text.AfterDelimiter(text as nullable text, delimiter as text, optional index as any) as any

¿Qué hace?

Extrae el texto antes o después de un delimitador. El parámetro index permite especificar la ocurrencia (0 = primera, {0, RelativePosition.FromEnd} = última).

Ejemplo

Text.BeforeDelimiter("nombre@empresa.com", "@")
// "nombre"

Text.AfterDelimiter("nombre@empresa.com", "@")
// "empresa.com"

// Última ocurrencia del delimitador
Text.AfterDelimiter("C:/datos/2024/archivo.csv", "/", {0, RelativePosition.FromEnd})
// "archivo.csv"
📌 Buena práctica: Prefiere Text.BeforeDelimiter / Text.AfterDelimiter sobre combinaciones de Text.PositionOf + Text.Middle. El código queda más legible y mantenible.

Text.BetweenDelimiters

Intermedio

Sintaxis

Text.BetweenDelimiters(text as nullable text, startDelimiter as text, endDelimiter as text, optional startIndex as any, optional endIndex as any) as any

¿Qué hace?

Extrae el texto comprendido entre dos delimitadores. Ideal para parsear cadenas con estructura definida.

Ejemplo

Text.BetweenDelimiters("[2024-01-15] Venta Madrid", "[", "]")
// "2024-01-15"

Text.BetweenDelimiters("SELECT * FROM [Ventas] WHERE", "[", "]")
// "Ventas"
📐

Relleno (Padding)

Text.PadStart / Text.PadEnd

Intermedio

Sintaxis

Text.PadStart(text as nullable text, count as number, optional character as nullable text) as nullable text
Text.PadEnd(text as nullable text, count as number, optional character as nullable text) as nullable text

¿Qué hace?

Rellena un texto al inicio (PadStart) o al final (PadEnd) hasta alcanzar la longitud count. Por defecto rellena con espacios, pero puedes especificar otro carácter.

Ejemplo

Text.PadStart("42", 6, "0")   // "000042"
Text.PadEnd("ES", 5, "-")     // "ES---"

// Normalizar códigos postales españoles (5 dígitos)
Text.PadStart(Text.From([CodigoPostal]), 5, "0")
// 28 → "00028", 8001 → "08001"
💡 Tip kawaii: Text.PadStart con ceros es el truco clásico para normalizar códigos numéricos que deben tener longitud fija, como códigos postales o IDs.
🔄

Conversión

Text.From

Principiante

Sintaxis

Text.From(value as any, optional culture as nullable text) as nullable text

¿Qué hace?

Convierte cualquier valor (número, fecha, lógico…) a su representación como texto. Es la función de conversión a texto más versátil de M.

Ejemplo

Text.From(2024)            // "2024"
Text.From(true)            // "true"
Text.From(3.14, "es-ES")   // "3,14" (con coma decimal)
Text.From(#date(2024,1,15)) // "2024-01-15"

Number.FromText

Principiante

Sintaxis

Number.FromText(text as nullable text, optional culture as nullable text) as nullable number

¿Qué hace?

Convierte un texto que representa un número a tipo numérico. Permite especificar la cultura para manejar separadores decimales y de miles.

Ejemplo

Number.FromText("1234.56")            // 1234.56
Number.FromText("1.234,56", "es-ES")  // 1234.56 (formato español)
Number.FromText("€1.234,56", "es-ES") // Error — quita el símbolo primero
🎨

Formato

Text.Format

Intermedio

Sintaxis

Text.Format(formatString as text, arguments as any, optional culture as nullable text) as text

¿Qué hace?

Construye un texto interpolando valores en una plantilla de formato. Los marcadores de posición son #{0}, #{1}, etc. (o claves si pasas un record).

Ejemplo

// Con lista de argumentos
Text.Format("Hola #{0}, tienes #{1} mensajes", {"María", 5})
// "Hola María, tienes 5 mensajes"

// Con record (más legible)
Text.Format("#{ciudad} registró #{ventas} ventas en #{año}",
  [ciudad = "Madrid", ventas = 1500, año = 2024])
// "Madrid registró 1500 ventas en 2024"
📌 Buena práctica: Usa Text.Format con records cuando tienes más de 2-3 valores a interpolar. Los nombres de clave hacen el código mucho más legible que índices numéricos.
🚀 ¡Dominas el texto! Ahora explora las Funciones de Número para operaciones matemáticas y de redondeo avanzadas.