“Tambahkan URL JavaScript Slash Trailing” Kode Jawaban

Tambahkan URL JavaScript Slash Trailing

// Add trailing slash even when a query is present.
// supported in all modern browsers
let url = new URL("a?foo=bar", "https://example.com");

if (url.pathname[url.pathname.length - 1] != "/") {
	url.pathname += "/";
}

// https://example.com/a/?foo=bar
console.log(url.toString());
XenoBino

JS Tambahkan Slash Trailing ke URL (jika tidak ada)

var lastChar = url.substr(-1); // Selects the last character
if (lastChar != '/') {         // If the last character is not a slash
   url = url + '/';            // Append a slash to it.
}

// The temporary variable name can be omitted, and directly embedded in the assertion:

if (url.substr(-1) != '/') url += '/';

// Since the goal is changing the url with a one-liner, the following solution can also be used:

url = url.replace(/\/?$/, '/');
// If the trailing slash exists, it is replaced with /.
// If the trailing slash does not exist, a / is appended to the end (to be exact: The trailing anchor is replaced with /).
Ill Iguana

Jawaban yang mirip dengan “Tambahkan URL JavaScript Slash Trailing”

Pertanyaan yang mirip dengan “Tambahkan URL JavaScript Slash Trailing”

Lebih banyak jawaban terkait untuk “Tambahkan URL JavaScript Slash Trailing” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya