2012-07-17 10 views
27

Sto realizzando una piccola app Web in cui un utente inserisce un URL del server dal quale carica un carico di dati con una richiesta AJAX.javascript/jquery aggiungi la barra finale alla url (se non presente)

Poiché l'utente deve immettere manualmente l'URL, in genere le persone dimenticano la barra finale, anche se è richiesta (poiché alcuni dati vengono aggiunti all'URL immesso). Ho bisogno di un modo per verificare se la barra è presente e, in caso contrario, aggiungerla.

Questo sembra un problema per il quale jQuery avrebbe una sola riga, qualcuno sa come farlo o dovrei scrivere una funzione JS?

+4

se (yourString.charAt (yourString.length-1) = '/') {yourString + = '/'} – TheZ

+0

... sul serio. scrivi tu stesso il codice hai passato più tempo a fare questa domanda, che avresti speso a scrivere il codice. – c69

+0

@TheZ 'substr' vuole il tuo amore, anche ... – c69

risposta

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

Il nome della variabile temporanea può essere omesso, e direttamente incorporato nel asserzione:

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

Poiché l'obiettivo sta cambiando l'URL con una battuta, la seguente soluzione può essere utilizzata anche:

url = url.replace(/\/?$/, '/'); 
  • Se esiste la barra finale, esso è sostituito con /.
  • Se la barra finale non esiste, uno / viene aggiunto alla fine (per essere precisi: l'ancoraggio finale viene sostituito con /).
+0

Perfetto! Grazie a tutti :) – jackweirdy

7

ho aggiunto alla soluzione regex per ospitare stringhe di query:

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

url.replace(/\/?(\?|#|$)/, '/$1') 
+1

buona regex - fyi, il tuo violino manca il segno di spunta per "#", (anche se ovviamente la tua risposta ce l'ha.) – jlee

+0

Aspetto interessante. – jscripter

9
url += url.endsWith("/") ? "" : "/" 
2

Prima di trovare questa domanda e le sue risposte ho creato il mio approccio. Lo post qui perché non vedo qualcosa di simile.

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); 
    } 
} 
+0

'history.replaceState' è esattamente quello che stavo cercando. Consente un'aggiunta della barra finale * senza * un reindirizzamento http 303 completo. Grazie mille :) – oxalorg

0

Non tutti gli URL possono essere completati con barra alla fine. Esistono almeno diverse condizioni che non ne consentono:

  • La stringa dopo l'ultima barra esistente è qualcosa come index.html.
  • Ci sono parametri: /page?foo=1&bar=2.
  • C'è un collegamento al frammento: /page#tomato.

Ho scritto una funzione per l'aggiunta di barra se nessuno dei casi precedenti è presente. Ci sono anche due funzioni aggiuntive per verificare la possibilità di aggiungere la barra e per rompere l'URL in parti. L'ultimo non è mio, ho dato un link a quello originale.

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) 
 
    }; 
 
}

Ci potrebbe anche essere diversi casi in cui l'aggiunta di barra non è possibile. Se ne conosci qualcuno, per favore commenta la mia risposta.

1

questo funziona così:

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

Esempio:

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); 

uscita:!

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