On Jun 30, 8:41 am, "Evertjan." <exjxw.hannivo...@interxnl.netwrote:
d d wrote on 30 jun 2007 in comp.lang.javascript:
Evertjan. wrote:
d d wrote on 30 jun 2007 in comp.lang.javascript:
var mystring="For $100 (optional) blah ($150.00)";
var start=mystring.lastIndexOf("$")+1;
var end=mystring.lastIndexOf(")");
var val=mystring.substring(start,end);
Regex:
var myString = 'For $100 (optional) blah ($150.00)';
var result = myString.replace(/^.*?\(\$(.*)?\)$/,'$1');
Cool!! I always try to avoid using Regular expressions.
Mostly because (a) they're impossible for humans to
understand, and (2) I'm a human ;-)
If you're an experienced regexp'er then they're cool.
But don't expect anyone else to understand them. Of
course that in itself can be good for job security ;-)
Do you mean I should ask money for it?
Regex is very powerfull, fits nicely in javascipt
and can be learned in 2 nights.
I would advice you to spend the time.
That's good advice. However, "2 nights" may not suffice.
var result = myString.replace(/^.*?\(\$(.*)?\)$/,'$1');
will produce an incorrect result, for example, with:
var myString = 'For $100 (optional) ($300.00) blah ($150.00)';
There are a number of things wrong in the construction of the regular
expression you have proposed, but in particular "?" seems to be
misused or misplaced, or both.
Great care is always required in composing regular expressions, and
even those with a high level of competence in the area need to
carefully test that they produce the desired result. They are
extremely useful, but they are in my experience, not at all easy to
master and use effectively.
var m;
if ( m = myString.match( /^.*\(\$(\d+\.\d{2})\)$/ ) ) {
alert( "Matched: " + m[1] );
}
may serve better.
--
../rh