1

This is what I've got so far:

var source = '>R$11111</b>';
var price = source.match(/[^R$]\d+/);

The 'source' is a little bit of a innerHTML insert, but I've got that down.

The problem is the 'price' MUST be in-between 'R$' and '</b>', no matter what is between them, from 1 to infinity. What I've got there will work, but when I take out 'R$' or '</b>' from it, it still finds the value and an extra character.

So basically I just need help with making it so it will only pick up the value between 'R$' and '</b>' when both are present.

***OR from R$ to the end of the string. But no space between R$ and the price.

2
  • @MarkReed </b> I think Commented May 25, 2012 at 2:01
  • When you say "innerHTML", you're not saying it came from using .innerHTML on a DOM element, are you? If so, it would be better to drill down to the proper element, and deal just with the text content. Commented May 25, 2012 at 2:08

3 Answers 3

4

Well, [^R$] matches "exactly one character that is neither an R nor a $", so that's probably not what you want.

var price = source.match(/R\$(\d+)/)[1];

Or if the price might not be all digits:

var price = source.match(/R\$(.*?)<\/b>/)[1];

The important thing is the parentheses around the part you care about, which cause whatever text matches what's in between the parentheses to be included in the returned value of the match as the second element of the array (the first being the part of the text that matches the whole regular expression).

If the string might not match the regex, then it's better to do it in two steps:

var match = source.match(/whichever/);
if (match) {
    price = match[1]; 
} else {
    console.log("no price found.");
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think the first approach (white-listing) is better than the second approach (black-listing) even if the price isn't all digits. Just adjust what characters are allowed. e.g. source.match(/R\$([\d.]+)/)[1]
1
var source = '>R$11111</b>';
var price = source.match(/R\$(\d+)<\/b>/);

if (price)
    console.log(price[1]); // 11111

Comments

0

Here is a non-regex solution in case someone is interested:

function getPrice(str, start, end){
    var first = str.indexOf(start),
        last = str.lastIndexOf(end);

    return ~first ?
                str.slice(first + start.length, (~last ? last : str.length))
                    .replace(/^\s+/, "")
            :
                str;
}

var source = "...R$  21112</b>...";

console.log(getPrice(source, "R$", "</b>")); //"21112"
console.log(getPrice(source, "R$", "nomatch")); //"21112</b>..."
console.log(getPrice(source, "nomatch", "</b>")); //"...R$  21112</b>..."

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.