开发者

Parsing special strings within a text (eg. "%var%")?

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

eg. "move 10 10 line 50 50"

move and line are commands

开发者_StackOverflow中文版

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?


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:

  • Search and Don't Replace


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜