View Full Version : String Parser
Astro-Boy
07-23-2002, 04:25 AM
function qq(str) {
while (str.indexOf('$') != -1) {
str = str.replace(/\$[^\s\W]+/,eval(str.match(/\$([^\s\W]+)/,"$1")[1]));
}
return str;
}
Usage:
var greet = 'hello'; var name = 'john';
alert(qq('$greet there $name!'));
Not overly useful, I just hate having to 'string '+var+' more strings' all the time :P
There are some limitations (vars must be global, etc), but maybe someone will find it helpful. I certainly have :)
- Mark
Cloudski
07-23-2002, 06:26 AM
Well, it is interesting to say the least... nice work... :thumbsup:
Roy Sinclair
07-24-2002, 01:56 AM
There are some limitations (vars must be global, etc), but maybe someone will find it helpful. I certainly have
There is a way to make local variables and still use your function:
<html>
<head>
<title>Testing</title>
<script type="text/javascript">
function qq(str)
{
while (str.indexOf('$') != -1)
{
str = str.replace(/\$[^\s\W]+/,eval(str.match(/\$([^\s\W]+)/,"$1")[1]));
}
return str;
}
</script>
</head>
<body>
<script type="text/javascript">
var a = "A"
var b = "B"
document.write(qq('$a but not $b'))
</script>
<hr />
<script type="text/javascript">
function aTest()
{
this.c = "C"
this.d = "D"
this.qq = qq;
document.write(qq('$c but not $d'))
}
aTest()
</script>
</body>
</html>
Rather than declare local variables using the var keyword, instead make them as objects of the function. Also make the qq function a property of the local function and then you can use it to show the contents of those localized variables.
mordred
07-24-2002, 12:04 PM
I'm a firm believer that eval() is inherently evil. So I would like to point out an alternative to it for this interesting function:
function qq(str) {
while (str.indexOf('$') != -1) {
str = str.replace(/\$[^\s\W]+/, this[str.match(/\$([^\s\W]+)/, "$1")[1]]);
}
return str;
}
When this function is called from the global scope, then "this" will point to window - in which all global variables are contained. If you call qq from a function, then it will try to find properties of that function instead, as outlined above by Roy Sinclair.
Just thinking about it, but have you also considered doing a global replace with backreference to a matched subpattern?
vBulletin® v3.8.2, Copyright ©2000-2009, Jelsoft Enterprises Ltd.