我有一个JavaScript字符串sentrptg2c#appqueue#sentrptg2c#vwemployees#
。想从字符串中获得特定值
我想通过RegExp或任何JavaScript函数获取最后一个字符串vwemployees
。
请建议一种在JavaScript中执行此操作的方法。
我有一个JavaScript字符串sentrptg2c#appqueue#sentrptg2c#vwemployees#
。想从字符串中获得特定值
我想通过RegExp或任何JavaScript函数获取最后一个字符串vwemployees
。
请建议一种在JavaScript中执行此操作的方法。
可以使用split
function:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
str = str.split("#");
str = str[str.length-2];
alert(str);
// Output: vwemployees
原因-2
是因为尾随#
的。如果没有尾随#
,那将是-1
。
这是JSFiddle。
var s = "...#value#";
var re = /#([^#]+)#^/;
var answer = re.match(s)[1] || null;
如果你确定字符串会被“#”分开,那么你可以在#上分割并获取最后一个条目......在拆分字符串之前,我剥离了最后一个#,如果它在那里。
var initialString = "sentrptg2c#appqueue#sentrptg2c#vwemployees#"
var parts = initialString.replace(/\#$/,"").split("#"); //this produces an array
if(parts.length > 0){
var result = parts[parts.length-1];
}
尝试类似this:
String.prototype.between = function(prefix, suffix) {
s = this;
var i = s.indexOf(prefix);
if (i >= 0) {
s = s.substring(i + prefix.length);
}
else {
return '';
}
if (suffix) {
i = s.indexOf(suffix);
if (i >= 0) {
s = s.substring(0, i);
}
else {
return '';
}
}
return s;
}
无幻数:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var ar = [];
ar = str.split('#');
ar.pop();
var o = ar.pop();
alert(o);
我已经尝试了一些正则表达式来做到这一点,但没有成功,并且还试图转换数组中的字符串以获取最后一个元素 – Ekky 2013-04-30 06:17:46
为什么要使用r egexp? – Mics 2013-04-30 06:18:06
,因为每次有新的关键字字符串将是动态的,所以我的正则表达式是正确的选择 – Ekky 2013-04-30 06:19:29