javascript - Eliminar la cadena al principio de una URL
Quiero eliminar la parte "www." del inicio de una cadena de URL
Por ejemplo, en estos casos de prueba:
por ejemplo, www.test.com → test.com
por ejemplo, www.testwww.com → testwww.com
por ejemplo, testwww.com → testwww.com (si no existe)
¿Necesito usar Regexp o hay una función inteligente?
Respuesta #1
Depende de lo que necesites, tienes un par de opciones, puedes hacer:
// this will replace the first occurrence of "www." and return "testwww.com"
"www.testwww.com".replace("www.", "");
// this will slice the first four characters and return "testwww.com"
"www.testwww.com".slice(4);
// this will replace the www. only if it is at the beginning
"www.testwww.com".replace(/^(www\.)/,"");
Respuesta #2
Sí, hay una RegExp, pero no necesitas usarla ni ninguna función "inteligente":
var url = "www.testwww.com";
var PREFIX = "www.";
if (url.startsWith(PREFIX)) {
// PREFIX is exactly at the beginning
url = url.slice(PREFIX.length);
}
Respuesta #3
Si la cadena siempre tiene el mismo formato, un simple substr() debería ser suficiente.
var newString = originalString.substr(4)
Respuesta #4
const removePrefix = (value, prefix) =>
value.startsWith(prefix) ? value.slice(prefix.length) : value;
