[英]Get string between first space character and '=' character
Basically, I would like to create a Javascript function to return me the string between the first space character and '=' character. 基本上,我想创建一个Javascript函数来向我返回第一个空格字符和'='字符之间的字符串。
For eg:- 例如:
ABC123 Mercedes Benz = 300,000
The function should return me Mercedes Benz. 该功能应返回梅赛德斯·奔驰。 Is there a way to do that?
有没有办法做到这一点?
You should use a regular expression : 您应该使用正则表达式 :
var myStr = "ABC123 Mercedes Benz = 300,000"
var targetStr = myStr.replace(/^[^\s]*\s(.*)=.*$/, "$1")
The replace
method returns a new string, so myStr
still holds its original value, but targetStr
has the matching portion. replace
方法返回一个新字符串,因此myStr
仍保留其原始值,但是targetStr
具有匹配的部分。
var myStr = "ABC123 Mercedes Benz = 300,000"
myStr = / [^=]+/.exec(myStr);
alert(myStr);
You should really post some of your own attempts rather than expect SO to do everything for you. 您应该真正发表自己的尝试,而不是期望SO为您做所有事情。 This should work for this specific case;
这应该适用于这种特定情况;
var get_second_word = function (string){
var p1 = string.indexOf(" "),//get position of first space
p2 = string.indexOf("="),//get position of =
len = p2 - p1,// length of chunk = pos of '=' - pos of first space
chunk = string.substr(p1, len); //get the substring
return chunk;
},
string = "ABC123 Mercedes Benz = 300,000",
word = get_second_word(string);
document.write(word);// prints 'Mercedes Benz'
Maybe not the best way, but 也许不是最好的方法,但是
function getSmth(str) {
var i = str.indexOf(' ') + 1;
var j = str.indexOf('=');
return str.substr(i, j - i - 1);
}
Try this: 尝试这个:
function getPartial(str)
{
var partial = '';
var io = str.indexOf(' ');
if (io > 0)
{
partial = str.substring(io);
var io2 = partial.indexOf('=');
if (io2 > 0)
{
partial = partial.substring(0, io2);
}
}
return partial;
}
var str = 'ABC123 Mercedes Benz = 300,000';
var partial = getPartial(str);
alert(partial);
var s = "ABC123 Mercedes Benz = 300,000";
s = s.substring(s.indexOf(" ")+1);
var result = s.substring(0, s.indexOf("=")-1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.