50

ユーザーがサーバーのURLを入力し、そこからAJAXリクエストを使用して大量のデータを取得する小さなWebアプリを作成しています。

ユーザーはURLを手動で入力する必要があるため、必要な場合でも、通常、末尾のスラッシュは忘れられます(入力されたURLに一部のデータが追加されるため)。スラッシュが存在するかどうかを確認し、存在しない場合は追加する方法が必要です。

これは、jQueryにワンライナーがある問題のようです。誰かがこれを行う方法を知っていますか、それともJS関数を作成する必要がありますか?

4

9 に答える 9

123
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.
}

一時変数名は省略でき、アサーションに直接埋め込むことができます。

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

目標はワンライナーでURLを変更することなので、次の解決策も使用できます。

url = url.replace(/\/?$/, '/');
  • 末尾のスラッシュが存在する場合は、に置き換えられ/ます。
  • 末尾のスラッシュが存在しない場合は、末尾にa/が追加されます(正確には、末尾のアンカーはに置き換えられ/ます)。
于 2012-07-17T21:54:22.837 に答える
48
url += url.endsWith("/") ? "" : "/"
于 2016-03-22T08:54:57.073 に答える
17

クエリ文字列に対応するために正規表現ソリューションに追加しました。

http://jsfiddle.net/hRheW/8/

url.replace(/\/?(\?|#|$)/, '/$1')
于 2013-07-16T16:54:26.677 に答える
9

これも機能します:

url = url.replace(/\/$|$/, '/');

例:

let urlWithoutSlash = 'https://www.example.com/path';
urlWithoutSlash = urlWithoutSlash.replace(/\/$|$/, '/');
console.log(urlWithoutSlash);

let urlWithSlash = 'https://www.example.com/path/';
urlWithSlash = urlWithoutSlash.replace(/\/$|$/, '/');
console.log(urlWithSlash);

出力:

https://www.example.com/path/
https://www.example.com/path/

末尾のスラッシュまたは末尾のスラッシュがないものを末尾のスラッシュに置き換えます。したがって、スラッシュが存在する場合は、スラッシュが1つに置き換えられます(基本的にはそのままにしておきます)。存在しない場合は、末尾にスラッシュが追加されます。

于 2017-11-08T22:48:17.857 に答える
4

あなたは次のようなことをすることができます:

var url = 'http://stackoverflow.com';

if (!url.match(/\/$/)) {
    url += '/';
}

証拠は次のとおりです:http://jsfiddle.net/matthewbj/FyLnH/

于 2012-07-17T21:56:40.380 に答える
3

このURLクラスは非常に優れています。パスを変更し、クエリパラメータとフラグメント識別子を処理するのに役立ちます。

function addTrailingSlash(u) {
    const url = new URL(u);
    url.pathname += url.pathname.endsWith("/") ? "" : "/";
    return url.toString();
}

addTrailingSlash('http://example.com/slug?page=2');
// result: "http://example.com/slug/?page=2"

MDNURLについてもっと読むことができます

于 2020-10-27T09:47:59.773 に答える
2

この質問とその答えを見つける前に、私は独自のアプローチを作成しました。似たようなものが見当たらないので、ここに投稿します。

function addSlashToUrl() {
    //If there is no trailing shash after the path in the url add it
    if (window.location.pathname.endsWith('/') === false) {
        var url = window.location.protocol + '//' + 
                window.location.host + 
                window.location.pathname + '/' + 
                window.location.search;

        window.history.replaceState(null, document.title, url);
    }
}
于 2016-10-28T08:49:26.097 に答える
0

すべてのURLの最後にスラッシュを付けることができるわけではありません。1つを許可しない条件が少なくともいくつかあります。

  • 最後の既存のスラッシュの後の文字列は、のようなものindex.htmlです。
  • パラメータがあります:/page?foo=1&bar=2
  • フラグメントへのリンクがあります:/page#tomato

上記のいずれにも当てはまらない場合にスラッシュを追加する関数を作成しました。スラッシュを追加する可能性をチェックするための、およびURLを部分に分割するための2つの追加機能もあります。最後のものは私のものではありません、私は元のものへのリンクを与えました。

const SLASH = '/';

function appendSlashToUrlIfIsPossible(url) {
  var resultingUrl = url;
  var slashAppendingPossible = slashAppendingIsPossible(url);

  if (slashAppendingPossible) {
    resultingUrl += SLASH;
  }

  return resultingUrl;
}

function slashAppendingIsPossible(url) {
  // Slash is possible to add to the end of url in following cases:
  //  - There is no slash standing as last symbol of URL.
  //  - There is no file extension (or there is no dot inside part called file name).
  //  - There are no parameters (even empty ones — single ? at the end of URL).
  //  - There is no link to a fragment (even empty one — single # mark at the end of URL).
  var slashAppendingPossible = false;

  var parsedUrl = parseUrl(url);

  // Checking for slash absence.
  var path = parsedUrl.path;
  var lastCharacterInPath = path.substr(-1);
  var noSlashInPathEnd = lastCharacterInPath !== SLASH;

  // Check for extension absence.
  const FILE_EXTENSION_REGEXP = /\.[^.]*$/;
  var noFileExtension = !FILE_EXTENSION_REGEXP.test(parsedUrl.file);

  // Check for parameters absence.
  var noParameters = parsedUrl.query.length === 0;
  // Check for link to fragment absence.
  var noLinkToFragment = parsedUrl.hash.length === 0;

  // All checks above cannot guarantee that there is no '?' or '#' symbol at the end of URL.
  // It is required to be checked manually.
  var NO_SLASH_HASH_OR_QUESTION_MARK_AT_STRING_END_REGEXP = /[^\/#?]$/;
  var noStopCharactersAtTheEndOfRelativePath = NO_SLASH_HASH_OR_QUESTION_MARK_AT_STRING_END_REGEXP.test(parsedUrl.relative);

  slashAppendingPossible = noSlashInPathEnd && noFileExtension && noParameters && noLinkToFragment && noStopCharactersAtTheEndOfRelativePath;

  return slashAppendingPossible;
}

// parseUrl function is based on following one:
// http://james.padolsey.com/javascript/parsing-urls-with-the-dom/.
function parseUrl(url) {
  var a = document.createElement('a');
  a.href = url;

  const DEFAULT_STRING = '';

  var getParametersAndValues = function (a) {
    var parametersAndValues = {};

    const QUESTION_MARK_IN_STRING_START_REGEXP = /^\?/;
    const PARAMETERS_DELIMITER = '&';
    const PARAMETER_VALUE_DELIMITER = '=';
    var parametersAndValuesStrings = a.search.replace(QUESTION_MARK_IN_STRING_START_REGEXP, DEFAULT_STRING).split(PARAMETERS_DELIMITER);
    var parametersAmount = parametersAndValuesStrings.length;

    for (let index = 0; index < parametersAmount; index++) {
      if (!parametersAndValuesStrings[index]) {
        continue;
      }

      let parameterAndValue = parametersAndValuesStrings[index].split(PARAMETER_VALUE_DELIMITER);
      let parameter = parameterAndValue[0];
      let value = parameterAndValue[1];

      parametersAndValues[parameter] = value;
    }

    return parametersAndValues;
  };

  const PROTOCOL_DELIMITER = ':';
  const SYMBOLS_AFTER_LAST_SLASH_AT_STRING_END_REGEXP = /\/([^\/?#]+)$/i;
  // Stub for the case when regexp match method returns null.
  const REGEXP_MATCH_STUB = [null, DEFAULT_STRING];
  const URL_FRAGMENT_MARK = '#';
  const NOT_SLASH_AT_STRING_START_REGEXP = /^([^\/])/;
  // Replace methods uses '$1' to place first capturing group.
  // In NOT_SLASH_AT_STRING_START_REGEXP regular expression that is the first
  // symbol in case something else, but not '/' has taken first position.
  const ORIGINAL_STRING_PREPENDED_BY_SLASH = '/$1';
  const URL_RELATIVE_PART_REGEXP = /tps?:\/\/[^\/]+(.+)/;
  const SLASH_AT_STRING_START_REGEXP = /^\//;
  const PATH_SEGMENTS_DELIMITER = '/';

  return {
    source: url,
    protocol: a.protocol.replace(PROTOCOL_DELIMITER, DEFAULT_STRING),
    host: a.hostname,
    port: a.port,
    query: a.search,
    parameters: getParametersAndValues(a),
    file: (a.pathname.match(SYMBOLS_AFTER_LAST_SLASH_AT_STRING_END_REGEXP) || REGEXP_MATCH_STUB)[1],
    hash: a.hash.replace(URL_FRAGMENT_MARK, DEFAULT_STRING),
    path: a.pathname.replace(NOT_SLASH_AT_STRING_START_REGEXP, ORIGINAL_STRING_PREPENDED_BY_SLASH),
    relative: (a.href.match(URL_RELATIVE_PART_REGEXP) || REGEXP_MATCH_STUB)[1],
    segments: a.pathname.replace(SLASH_AT_STRING_START_REGEXP, DEFAULT_STRING).split(PATH_SEGMENTS_DELIMITER)
  };
}

スラッシュを追加できない場合もあります。知っている人がいたら、私の答えをコメントしてください。

于 2017-02-05T19:12:47.543 に答える
0

http://example.comhttp://example.com/eeeなど、さまざまな入力を使用する場合。2番目のケースでは、末尾にスラッシュを追加しないでください。

ドメイン(ホスト)の後にのみ末尾のスラッシュを追加する.hrefを使用したシリアル化オプションがあります。

NodeJでは、

You would use the url module like this: 
const url = require ('url');
let jojo = url.parse('http://google.com')
console.log(jojo);

純粋なJSでは、

var url = document.getElementsByTagName('a')[0];
var myURL = "http://stackoverflow.com";
console.log(myURL.href);
于 2018-12-01T09:32:05.660 に答える