I want to remove the " www.
" part from the beginning of an URL string
For instance in these test cases:
eg www.test.com
→ test.com
eg www.testwww.com
→ testwww.com
eg testwww.com
→ testwww.com
(if it doesn't exist)
Do I need to use Regexp or is there a smart function?
Depends on what you need, you have a couple of choices, you can do:
// 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\.)/,"");
Yes, there is a RegExp but you don't need to use it or any "smart" function:
var url = "www.testwww.com";
var PREFIX = "www.";
if (url.startsWith(PREFIX)) {
// PREFIX is exactly at the beginning
url = url.slice(PREFIX.length);
}
如果字符串始终具有相同的格式,那么简单的substr()
就足够了。
var newString = originalStrint.substr(4)
You can overload the String prototype with a removePrefix function:
String.prototype.removePrefix = function (prefix) {
const hasPrefix = this.indexOf(prefix) === 0;
return hasPrefix ? this.substr(prefix.length) : this.toString();
};
usage:
const domain = "www.test.com".removePrefix("www."); // test.com
Either manually, like
var str = "www.test.com",
rmv = "www.";
str = str.slice( str.indexOf( rmv ) + rmv.length );
or just use .replace()
:
str = str.replace( rmv, '' );
Try the following
var original = 'www.test.com';
var stripped = original.substring(4);
其他方式:
Regex.Replace(urlString, "www.(.+)", "$1");
const removePrefix = (value, prefix) =>
value.startsWith(prefix) ? value.slice(prefix.length) : value;
您可以剪切 url 并使用 response.sendredirect(new url),这会将您带到与新 url 相同的页面
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.