2012-07-17 18 views
27

Estoy haciendo una pequeña aplicación web en la que un usuario ingresa una URL del servidor desde la cual extrae una carga de datos con una solicitud AJAX.javascript/jquery agregar una barra diagonal a la url (si no está presente)

Dado que el usuario tiene que ingresar la URL manualmente, la gente generalmente olvida la barra inclinada, aunque sea necesaria (ya que algunos datos se añaden a la URL ingresada). Necesito una forma de verificar si la barra inclinada está presente, y si no, agrégala.

Esto parece ser un problema para el que jQuery tendría una línea, ¿alguien sabe cómo hacer esto o debería escribir una función JS para ello?

+4

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

+0

... en serio. solo escribe el código tú mismo. Pasaste más tiempo haciendo esta pregunta, que hubieras pasado escribiendo el código. – c69

+0

@TheZ 'substr' quiere tu amor, también ... – c69

Respuesta

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

El nombre de la variable temporal puede ser omitido, y directamente incrustado en la afirmación:

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

Dado que el objetivo está cambiando la dirección URL con una sola línea, la siguiente solución también se puede utilizar:

url = url.replace(/\/?$/, '/'); 
  • Si existe la barra al final, es reemplazado con /.
  • Si la barra diagonal no existe, se agrega un / al final (para ser exactos: el ancla trasera se reemplaza por /).
+0

¡Perfecto! Gracias a todos :) – jackweirdy

7

he añadido a la solución de expresiones regulares para dar cabida a las cadenas de consulta:

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

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

good regex - fyi, a su violín le falta el cheque para '#', (aunque su respuesta obviamente lo tiene.) – jlee

+0

Aspecto interesante. – jscripter

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

Antes de encontrar esta pregunta y sus respuestas creé mi propio enfoque. Lo publico aquí porque no veo algo similar.

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' es exactamente lo que había estado buscando. Permite agregar barras inclinadas * sin * realizar una redirección completa de http 303. Muchas gracias :) – oxalorg

0

No todas las URL se pueden completar con una barra al final. Hay al menos varias condiciones que no permiten una:

  • Cadena después de la última barra existente es algo así como index.html.
  • Hay parámetros: /page?foo=1&bar=2.
  • Hay un enlace al fragmento: /page#tomato.

He escrito una función para agregar barras oblicuas si ninguno de los casos anteriores está presente. También hay dos funciones adicionales para verificar la posibilidad de agregar barras y romper URL en partes. El último no es mío, he dado un enlace al original.

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

También puede haber varios casos en los que la adición de barra no es posible. Si sabes algo, por favor comenta mi respuesta.

1

Esto funciona así:

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

Ejemplo:

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

de salida:!

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