1

I have a string with one or more placeholders in the following format: $([name])

The [name] can be any word (containing alfanumeric chars) and is case sensitive.

 Example1: 'The $(Quick) Brown fox jumps over the lazy dog'
 Example2: '$(the) $(Quick) Brown fox jumps over $(the) lazy dog'
 Example3: '$(the) $(Quick) Brown $(fox) jumps over $(the) lazy $(dog)'

What is the best way in javascript to retrieve all place holders so that we have following result:

 Example1: ['Quick']
 Example2: ['the', 'Quick', 'the']
 Example3: ['the', 'Quick', 'fox', 'the', 'dog']

I also need to retrieve a unique list of placeholders, thus:

 Example1: ['Quick']
 Example2: ['the', 'Quick']
 Example3: ['the', 'Quick', 'fox', 'dog']

Thank you.

3
  • 1
    Have you heard about regular expressions? Commented Jun 27, 2012 at 8:44
  • 2
    The placeholder tag has totally different meaning. Commented Jun 27, 2012 at 8:46
  • P.S. What have you tried? Commented Jun 27, 2012 at 8:55

3 Answers 3

3

As other answers have mentioned, your best approach is to use regular expression with the JavaScript string.match() function. My regular expression isn't the best it could be [whose is], but this should do the trick:

jsFiddle Demo

function getPlaceholders(str)
{
    var regex = /\$\((\w+)\)/g;
    var result = [];

    while (match = regex.exec(str))
    {
        result.push(match[1]);    
    }

    return result;
}

Thanks freakish

Sign up to request clarification or add additional context in comments.

1 Comment

Few modifications: use regex = /\$\((\w+)\)/g and arr = []; while(match=regex.exec(example1)){ arr.push((match[1])); } and we're there.
0

Use a regular expression with string's match function

Comments

0

Read this

http://net.tutsplus.com/tutorials/php/advanced-regular-expression-tips-and-techniques/

http://swtch.com/~rsc/regexp/regexp1.html

you can see more on Bookmark

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.