javascript - Supprimer la chaîne au début d'une URL
Je veux supprimer la partie « www. » du début d'une chaîne URL
Par exemple, dans ces cas de test :
par ex. www.test.com → test.com
par ex. www.testwww.com → testwww.com
par ex. testwww.com → testwww.com (si cela n'existe pas)
Ai-je besoin d’utiliser Regexp ou y a-t-il une fonction intelligente ?
Réponse #1
Cela dépend de ce dont vous avez besoin, vous avez quelques choix, vous pouvez faire :
// 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\.)/,"");
Réponse #2
Oui, il y a une RegExp mais vous n'avez pas besoin de l'utiliser ni d'utiliser une fonction « intelligente » :
var url = "www.testwww.com";
var PREFIX = "www.";
if (url.startsWith(PREFIX)) {
// PREFIX is exactly at the beginning
url = url.slice(PREFIX.length);
}
Réponse #3
Si la chaîne a toujours le même format, un simple substr() devrait suffire.
var newString = originalString.substr(4)
Réponse #4
const removePrefix = (value, prefix) =>
value.startsWith(prefix) ? value.slice(prefix.length) : value;
