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?
From stackoverflow
-
// 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; -
Another way:
text.match(/\$/g).length/2 == text.match(/\$[a-z]+\$/g).lengthThis counts the number of
$and compares it to the number of$foobar$.Georg : Isn't there a .length missing?Georg : btw: I like this solution very much.Gumbo : Woops. Thanks for the remark, gs.
0 comments:
Post a Comment