Basically, I would like to create a Javascript function to return me the string between the first space character and '=' character.
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.
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. 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.