views:

721

answers:

2

I need a javascript function which gets a string and returns false if the string contains
- Any unclosed dollar symbol
- Or a closed dollar symbol with something between dollars different than a series of characters

function validateFormat(text) {
// Do stuff
}

For example if text:

validateFormat("blab abalaba $something$ avava $affo$")  -> true
validateFormat("blab abalaba $something$ avava $ affo$") -> false because of the white space
validateFormat("blab abalaba $1so3mething$ avava $affo$") -> false because of the numbers
validateFormat("blab abalaba $something") -> false because of unclosed placeholder

Can someone help me?

+3  A: 
// delete all valid placeholders
text = text.replace(/\$[a-z]+\$/gi, "");

// are there any "$" left?
if (text.search(/\$/) != -1) {
    return false;
}
return true;

This is another solution:

matches = text.match(/\$[a-z]+\$|\$/gi);
if (matches) {
    for (var i = 0; i < matches.length; i++) {
        if (matches[i] == '$') { return false };
    }
}
return true;
Georg
+3  A: 

Another way:

text.match(/\$/g).length/2 == text.match(/\$[a-z]+\$/g).length

This counts the number of $ and compares it to the number of $foobar$.

Gumbo
Isn't there a .length missing?
Georg
btw: I like this solution very much.
Georg
Woops. Thanks for the remark, gs.
Gumbo