0

I have a string like this:

S(08-01-2008) I[18] ф4(579.1900 UAH) E(05-07-2009)R[5](117.1900) V[0](0.0000) Up(22-04-2009)

I need get Up value: 22-04-2009

4

3 回答 3

3

Try

'S(08-01-2008) I[18] ф4(579.1900 UAH) E(05-07-2009) R5 V0 Up(22-04-2009)'
 .match(/Up\(.+\)/g);

It returns an array of matched values, here ["Up(22-04-2009)"]

Value only could be:

'S(08-01-2008) I[18] ф4(579.1900 UAH) E(05-07-2009) R5 V0 Up(22-04-2009)'
 .match(/Up\(.+\)/g)[0].split(/\(|\)/)[1];

Or

'S(08-01-2008) I[18] ф4(579.1900 UAH) E(05-07-2009) R5 V0 Up(22-04-2009)'
 .match(/Up\(.+\)/g)[0].replace(/Up\(|\)/g,'');

If you're not sure 'Up(...)' exists in the string:

( 'S(08-01-2008) I[18] ф4(579.1900 UAH) E(05-07-2009) R5 V0 Up(22-04-2009)'
   .match(/Up\(.+\)/g) || ['not found'][0] ) 
 .replace(/Up\(|\)/g,'');
于 2012-08-30T11:35:51.820 回答
1
extract = yourString.substr( -11,10);

It will extract 10 chars starting by the 11th counting from end.

This assume that the up value is always at the end of your input string.

This one is much faster than regex, or split solutions if you just need one value.

More example at : http://www.bennadel.com/blog/2159-Using-Slice-Substring-And-Substr-In-Javascript.htm

于 2012-08-30T11:38:58.483 回答
1

You can easily match a regular expression or get some substring from a certain (or computed) position, but let's try to parse it with a regex and split:

var str = "S(08-01-2008) I[18] ф4(579.1900 UAH) E(05-07-2009)R[5](117.1900) V[0](0.0000) Up(22-04-2009)";

var parts = str.split(/\s*\(\s*(.+?)\s*\)\s*/);
var map = {};
for (var i=0; i+1<parts.length; i+=2)
    map[parts[i]] = parts[i+1];

Now, you can get the "Up" value from the map via

return map["Up"]; // "22-04-2009"

In contrast to the other answers, this will result in undefined if there is no "Up" value in the string instead of throwing an exception. Also, you can get the other values from the map if you need them, for example map["I[18] ф4"] is "I[18] ф4".

于 2012-08-30T11:47:04.547 回答