tags:

views:

65

answers:

3

Hi, I am supplying a Javascript function strings with commands (SVG path commands):

eg. "move 10 10 line 50 50"

move and line are commands

numbers are x, y coordinates

I would like to add special strings to these commands, that would instruct the function to use specific variables

eg. "move %mouseX%+1 %mouseY%+1"

where %mouseX% and %mouseY% would be the mouse x,y coordinates

How can I parse and replace these?

+2  A: 

You can use split method to split the string.

var arrSplitString = stringToSplit.split(' ');

and result will be an array. Then replace the corresponding index values with the desired one.

See split

To get the mouse position you can use e.PageX and e.PageY

See Mouse position

rahul
+3  A: 
var command = 'move %mouseX%+1 %mouseY%+1';
command = command.replace('%mouseX%', mouseX).replace('%mouseY%', mouseY);

Where mouseX and mouseY are the variables holding the mouse position.

BranTheMan
Makes I lot of sense.
RadiantHex
Glad it helps. If you don't want to hard-code the special variable names and think you could add more, CMS's answer is perfect for that.
BranTheMan
btw there is a problem, it only replaces the first occurrence!
RadiantHex
I found out that by writing it as /%mouseX%/g makes it work properly
RadiantHex
+6  A: 

For this type of string manipulation, as a starting point, you could take advantage of using a powerful feature of the String.prototype.replace function, using its callback function:

function replaceTokens(str, replacement) {
  return str.replace(/\%([^%]+)\%/g, function (string, match) {
    return replacement[match];
  });
}

replaceTokens("move %mouseX%+1 %mouseY%+1", {mouseX: 100, mouseY: 200});
// returns  "move 100+1 200+1"
replaceTokens("%foo% %bar%!!!", {foo: 'Hello', bar: 'World'});
// returns Hello World!!!
replaceTokens("I'm %name%, and I %action% %place%", {name: 'CMS',
  action: 'love',
  place:'StackOverflow'
}); // "I'm CMS, and I love StackOverflow"

That is only a simple example about the sort of things that you are able to do with this technique. This small function will make you able to do multiple %token% replacements in one step.

Recommended article:

CMS
Wow I really like this answer, thank you!
RadiantHex