javascript 如何在给定字符后选择子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7853154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to choose a substring after given character
提问by Alan Budzinski
I would like to save a substring to a javascript variable using regex unless there is a different/easier way. For example i have a link like this: http://www.youtube.com/watch?v=sEHN4t29oXY&feature=related
除非有不同/更简单的方法,否则我想使用正则表达式将子字符串保存到 javascript 变量中。例如我有一个这样的链接:http: //www.youtube.com/watch?v=sEHN4t29oXY&feature=related
I want to only get sEHN4t29oXY&feature=related so i guess i would have to check for the first equal sign to appear and after that save the rest of that string into the variable.. please help, thanks
我只想得到 sEHN4t29oXY&feature=related 所以我想我必须检查第一个等号是否出现,然后将该字符串的其余部分保存到变量中..请帮忙,谢谢
采纳答案by user973254
not with regex, but simple too, because first url part is static and has 23 symbols length
不是正则表达式,但也很简单,因为第一个 url 部分是静态的并且有 23 个符号长度
'http://www.youtube.com/watch?v=sEHN4t29oXY&feature=related'.substr(23)
Oh, I've made a mistake, he wants another part, so actual code will looks like:
哦,我犯了一个错误,他想要另一部分,所以实际代码看起来像:
'http://www.youtube.com/watch?v=sEHN4t29oXY&feature=related'.substr(31)
回答by Bryan Field
Efficient:
高效的:
variable = variable.substring(variable.indexOf('?v=')+3) // First occurence of ?v=
Regular expression:
正则表达式:
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.
回答by gilly3
Like so:
像这样:
var match = /\?v=(.+)/.exec(link)[1];
回答by zzzzBov
I think the easiest way of getting a parameter out of a query string is to use the following code:
我认为从查询字符串中获取参数的最简单方法是使用以下代码:
var u = new URI('http://www.youtube.com/watch?v=sEHN4t29oXY&feature=related');
u.getQuery('v') //sEHN4t29oXY
u.getQuery('feature') //related
Now, someone should be yelling at me with a comment like:
现在,应该有人用这样的评论对我大喊大叫:
There's no URI object in JavaScript, you can't do that!!!11one
JavaScript 中没有 URI 对象,你不能这样做!!!11one
And that someone would be right, so here you go:
并且有人是对的,所以你去:
/**
* 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));