2011-10-21 5 views
5

Je souhaite enregistrer une sous-chaîne dans une variable javascript en utilisant regex sauf s'il existe un moyen différent/plus simple. Par exemple, j'ai un lien comme celui-ci: http://www.youtube.com/watch?v=sEHN4t29oXY&feature=relatedComment choisir une sous-chaîne après un caractère donné

Je veux seulement obtenir sEHN4t29oXY & fonction = racontais donc je suppose que je dois vérifier le premier signe égal à apparaître et après que sauver le reste de cette chaîne dans la variable .. s'il vous plaît aider, merci

+0

est le but de simplement obtenir des paramètres d'URL? – zzzzBov

Répondre

3

pas avec regex, mais simple aussi, parce que la première partie de l'URL est statique et a 23 symboles longueur

'http://www.youtube.com/watch?v=sEHN4t29oXY&feature=related'.substr(23) 

Oh, je l'ai fait une erreur, il veut une autre partie, le code si réelle volonté ressemble:

'http://www.youtube.com/watch?v=sEHN4t29oXY&feature=related'.substr(31) 
+0

En fait, encore plus efficace que ma solution. Juste nécessite un format exact pour l'URL d'origine. –

10

efficace:

variable = variable.substring(variable.indexOf('?v=')+3) // First occurence of ?v= 

expression régulière:

variable = variable.replace(/.*\?v=/, '') // Replace last occurrence of ?v= and any characters before it (except \r or \n) with nothing. ? has special meaning, that is why the \ is required 
variable = variable.replace(/.*?\?v=/, '') // Variation to replace first occurrence. 
+0

je vous remercie pour la réponse –

+0

Si cette réponse vous a aidé, s'il vous plaît marquer comme accepté. –

4

comme ceci:

var match = /\?v=(.+)/.exec(link)[1]; 
+0

Assurez-vous simplement de vérifier null après, au cas où il n'y avait pas de correspondance ... –

+0

S'il n'y a pas de correspondance. Cela va jeter une erreur. –

0

Je pense que la meilleure façon d'obtenir un paramètre sur une chaîne de requête est d'utiliser le code suivant:

var u = new URI('http://www.youtube.com/watch?v=sEHN4t29oXY&feature=related'); 
u.getQuery('v') //sEHN4t29oXY 
u.getQuery('feature') //related 

Maintenant, quelqu'un doit être à me crier dessus avec un commentaire comme:

Il n'y a pas l'objet URI en JavaScript, vous ne pouvez pas le faire !!! 11one

Et que quelqu'un serait bon, alors là, vous allez:

/** 
* URI.js by zzzzBov 
*/ 
(function (w) { 
    "use strict"; 
    var URI = function (str) { 
    if (!this) { 
     return new URI(str); 
    } 
    if (!str) { 
     str = window.location.toString(); 
    } 
    var parts, uriRegEx, hostParts; 
    //http://labs.apache.org/webarch/uri/rfc/rfc3986.html#regexp 
    uriRegEx = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/; 
    str = str.toString(); 
    parts = uriRegEx.exec(str); 
    this.protocol = parts[1] || ''; 
    this.host = parts[4] || ''; 
    this.pathname = parts[5] || ''; 
    this.search = parts[6] || ''; 
    this.hash = parts[8] || ''; 
    //logic to break host into hostname:port 
    hostParts = this.host.split(':'); 
    this.hostname = hostParts[0] || ''; 
    this.port = hostParts[1] || ''; 
    }; 
    URI.prototype = { 
    getQuery: function (i) { 
     var o; 
     o = URI.parseQueryString(this.search); 
     return i === undefined ? o : o[i]; 
    }, 
    setQuery: function (val) { 
     var s; 
     s = URI.buildQueryString(val); 
     this.search = s.length ? '?' + s : s; 
    }, 
    toString: function() { 
     return this.protocol + '//' + this.host + this.pathname + this.search + this.hash; 
    } 
    }; 
    URI.parseQueryString = function (str) { 
    var obj, vars, i, l, data, rawKey, rawVal, key, val; 
    obj = {}; 
    if (!str) { 
     return obj; 
    } 
    //make sure it's a string 
    str = str.toString(); 
    if (!str.length || str === '?') { 
     return obj; 
    } 
    //remove `?` if it is the first char 
    if (str[0] === '?') { 
     str = str.substr(1); 
    } 
    vars = str.split('&'); 
    for (i = 0, l = vars.length; i < l; i += 1) { 
     data = vars[i].split('='); 
     rawKey = data[0]; 
     rawVal = data.length > 1 ? data[1] : ''; 
     //if there's a key, add a value 
     if (rawKey) { 
     key = URI.decode(rawKey); 
     val = URI.decode(rawVal); 
     //check if obj[key] is set 
     if (obj.hasOwnProperty(key)) { 
      if (typeof obj[key] === 'string') { 
      //if it's a string turn it to an array 
      obj[key] = [ obj[key], val ]; 
      } else { 
      //it's an array, push 
      obj[key].push(val); 
      } 
     } else { 
      obj[key] = val; 
     } 
     } 
    } 
    return obj; 
    }; 
    URI.buildQueryString = function (obj) { 
    var arr, key, val, i; 
    function build(key, value) { 
     var eKey, eValue; 
     eKey = URI.encode(key); 
     eValue = URI.encode(value); 
     if (eValue) { 
     arr.push(eKey + '=' + eValue); 
     } else { 
     arr.push(eKey); 
     } 
    } 
    arr = []; 
    for (key in obj) { 
     if (obj.hasOwnProperty(key)) { 
     val = obj[key]; 
     //isArray check 
     if (Object.prototype.toString.call(val) === '[object Array]') { 
      for (i in val) { 
      if (val.hasOwnProperty(i)) { 
       build(key, val[i]); 
      } 
      } 
     } else { 
      build(key, val); 
     } 
     } 
    } 
    return arr.join('&'); 
    }; 
    URI.decode = decodeURIComponent; 
    URI.encode = encodeURIComponent; 
    w.URI = URI; 
}(window)); 
Questions connexes