473,320 Members | 1,862 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Testing wheather string conversion is possible

Assume the following JavaScript function:

function bracketize(s)
{
return '['+s+']';
}

This function which doesn't assume anything about its argument
except that it must be convertible to a string.

I would now like to enhance this function, so that it does not
complain an error ("cant't convert s to string") for those cases
where s happens to be not convertable to a string:

function bracketize(s)
{
return
(`s can be converted to string`)
? '['+s+']'
: null
;
}

How can I write the condition `s can be converted to string` in JavaScript?

Ronald
Jul 23 '05 #1
9 1799
On 18 Nov 2004 04:05:48 -0800, Ronald Fischer <ro*****@eml.cc> wrote:
Assume the following JavaScript function:

function bracketize(s)
{
return '['+s+']';
}

This function which doesn't assume anything about its argument
except that it must be convertible to a string.


This causes a problem because *everything* can be converted to a string.
That conversion may not be particularly useful, but it can be done
nevertheless.

If you want to know if something *is* a string, you can use the expression

'string' == typeof <variable>

which will only evaluate to true if <variable> is a string.

If you did actually mean "convertible to a string", you'll have to be more
specific. What characterises something that, in your opinion, cannot be
converted?

[snip]

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #2
Ronald Fischer wrote:
function bracketize(s)
{
return
(`s can be converted to string`)
? '['+s+']'
: null
;
}

How can I write the condition `s can be converted to string` in
JavaScript?


Given that an object might implement its own toString method but fail to
convert because of some error, the only guaranteed way to know whether it
can be converted to a string is to do the conversion and handle the error:

function bracketize(s) {
try {
return '['+s+']';
} catch(e) {
return null;
}
}

N.B. This function will produce different output on different browsers. For
example, if an object's toString method throws an error Mozilla will return
null but IE will catch and ignore the error from toString so you get '[]'.
You get a more stable result of you call toString yourself:

function bracketize(s) {
try {
return '['+(s.toString?s.toString():s)+']';
} catch(e) {
return null;
}
}
Jul 23 '05 #3
"Michael Winter" <M.******@blueyonder.co.invalid> wrote in message news:<opshnubpq7x13kvk@atlantis>...
On 18 Nov 2004 04:05:48 -0800, Ronald Fischer <ro*****@eml.cc> wrote:
Assume the following JavaScript function:

function bracketize(s)
{
return '['+s+']';
}

This function which doesn't assume anything about its argument
except that it must be convertible to a string.


This causes a problem because *everything* can be converted to a string.
That conversion may not be particularly useful, but it can be done
nevertheless.


This is what I thought at first too, but it turned out to be not true. Maybe
I should give some background on this:

We have a general utility function which tests wheather a string is
empty:
return s==null || s=='';

This function ends up to be called in a context where s is sometimes not
a string, but still this test is done for any object s - this may seem
to be weird, but assume for the moment that this makes perfectly sense
in this context.

Now the problem is that JavaScript occasionally complains

"Can't convert s to string"

as I can see in the logfiles. So there must be cases where a conversion
to string is not possible.

I can imagine one, although very pathological, case where this could
happen: It must be that s is an object where no "toString" method exists.
Can this be possible? Can such a property, which is inherited from
Object, be dropped at run-time?

But maybe more realistic cases are possible:

Of course it is conceivable that the error message does not come
from the JavaScript engine, but from a custom toString method attached
to the object s (which is likely an object from a third-party library
we are using); but when I researched the discussions in the
usenet, I did find a few threads mentioning too the "can't convert ...
to string" message, so it seems to me that it indeed comes from
JavaScript.

Ronald
Jul 23 '05 #4
On 19 Nov 2004 00:17:26 -0800, Ronald Fischer <ro*****@eml.cc> wrote:
[T]here must be cases where a conversion to string is not possible.

I can imagine one, although very pathological, case where this could
happen: It must be that s is an object where no "toString" method
exists. Can this be possible? Can such a property, which is inherited
from Object, be dropped at run-time?
Potentially. For an object to be converted to a string, it must possess
either a toString or valueOf method. They are checked in that order. If
neither are objects or, when evaluted, one is an object that doesn't
implement the internal [[Call]] method, an exception is generated.

var o = new Object();
String(o); // "[Object object]"
o.toString = void 0; // Assign (undefined)
String(o); // Error

As you said, it would be a very unusual situation where someone would
intentionally remove the toString method. I can see reason to create your
own (I do when needed), but not remove it entirely.

[snip]
Of course it is conceivable that the error message does not come from
the JavaScript engine, but from a custom toString method attached to the
object s (which is likely an object from a third-party library we are
using);


Might I ask what environment you are using?

[snip]

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #5
Ronald Fischer wrote:
"Michael Winter" <M.******@blueyonder.co.invalid> wrote in message news:<opshnubpq7x13kvk@atlantis>...
On 18 Nov 2004 04:05:48 -0800, Ronald Fischer <ro*****@eml.cc> wrote:
Assume the following JavaScript function:

function bracketize(s)
{
return '['+s+']';
}

This function which doesn't assume anything about its argument
except that it must be convertible to a string.
This causes a problem because *everything* can be converted to a string.
That conversion may not be particularly useful, but it can be done
nevertheless.


This is what I thought at first too, but it turned out to be not true. Maybe
I should give some background on this:

We have a general utility function which tests wheather a string is
empty:
return s==null || s=='';

This function ends up to be called in a context where s is sometimes not
a string, but still this test is done for any object s - this may seem
to be weird, but assume for the moment that this makes perfectly sense
in this context.

Now the problem is that JavaScript occasionally complains

"Can't convert s to string"

as I can see in the logfiles. So there must be cases where a conversion
to string is not possible.


I'd like to see a small, working code sample that demonstrates this behaviour, because I've never seen it.
For example:

<script type="text/javascript">
function test(s) {
document.write('[' + s + ']');
}
test();
</script>

outputs: [undefined]
Of course it is conceivable that the error message does not come
from the JavaScript engine, but from a custom toString method attached
to the object s (which is likely an object from a third-party library
we are using); but when I researched the discussions in the
usenet, I did find a few threads mentioning too the "can't convert ...
to string" message, so it seems to me that it indeed comes from
JavaScript.


I can't duplicate the exact error, but if you attempt to access something you do not have access to, I
read some references to the error you are receiving on google. Something like:

<iframe name="foo" src="http://www.microsoft.com" onload="test();"></iframe>
<script type="text/javascript">
function test() {
var bar = window.frames['foo'].location;
alert(bar);
}
</script>

Gives "Access is denied" in IE and "Error: uncaught exception: [Exception... "Could not convert JavaScript
argument arg 0 [nsIDOMWindowInternal.alert]" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)"
location: "JS frame :: file:///c:/DOCUME~1/grantw/LOCALS~1/Temp/hs~new.htm :: test :: line 13" data: no]"
in Firefox.

Maybe other browsers, other circumstances, it would produce "Can't convert ... to string".

You could _try_ "return '[' + String(s) + ']';" but I'm guessing that in the circumstances in which you
receive the error, there is nothing you can do to prevent the problem, since as my first example
demonstrates, even an undefined value gets converted to a valid string, so anything else should.

--
Grant Wagner <gw*****@agricoreunited.com>
comp.lang.javascript FAQ - http://jibbering.com/faq

Jul 23 '05 #6
"Michael Winter" <M.******@blueyonder.co.invalid> wrote in message news:<opshpws3xsx13kvk@atlantis>...
On 19 Nov 2004 00:17:26 -0800, Ronald Fischer <ro*****@eml.cc> wrote:
Of course it is conceivable that the error message does not come from
the JavaScript engine, but from a custom toString method attached to the
object s (which is likely an object from a third-party library we are
using);


Might I ask what environment you are using?


The Broadvision framework (including a (slightly modified) JavaScript), running
under HP-UX.

Ronald
Jul 23 '05 #7
Grant Wagner <gw*****@agricoreunited.com> wrote in message news:<41***************@agricoreunited.com>...
I'd like to see a small, working code sample that demonstrates this behaviour, because I've never seen it.
So would I. The problem is that this behavious is not reproducible in the
lab. I know its existence only from our trace files, but whenever I try
to run similar examples manually, everything works as expected.
I can't duplicate the exact error, but if you attempt to access something you do not have access to, I
read some references to the error you are receiving on google. Something like:

<iframe name="foo" src="http://www.microsoft.com" onload="test();"></iframe>
<script type="text/javascript">


I searched on Google, but all cases relate to client-side JavaScript only
(which we never had a problem with), and they didn't seem to be related
to my problem anyway....

Ronald
Jul 23 '05 #8
Ronald Fischer wrote:
Grant Wagner <gw*****@agricoreunited.com> wrote in message news:<41***************@agricoreunited.com>...
I'd like to see a small, working code sample that demonstrates this behaviour, because I've never seen it.


So would I. The problem is that this behavious is not reproducible in the
lab. I know its existence only from our trace files, but whenever I try
to run similar examples manually, everything works as expected.
I can't duplicate the exact error, but if you attempt to access something you do not have access to, I
read some references to the error you are receiving on google. Something like:

<iframe name="foo" src="http://www.microsoft.com" onload="test();"></iframe>
<script type="text/javascript">


I searched on Google, but all cases relate to client-side JavaScript only
(which we never had a problem with), and they didn't seem to be related
to my problem anyway....


I wasn't aware you were referring to server-side JavaScript under BroadVision. Yes, I've seen BroadVision return
an object that can not be converted to a string. I can't remember the specific circumstances, nor what I did to
resolve it. However, you have to be aware of circumstances when you are returning BVI_ objects and when you are
returning JavaScript objects. For example:

// returns a BVI_Value object:
var aBviValueObject = aBviTable.get(0, "column_name");
// which you should access using:
Response.write(aBviValueObject.stringValue);

However:

// returns a String:
aBviTable.cursor = 0;
var aString = aBviTable.column_name;
// which can be accessed simply by:
Response.write(aString);

--
Grant Wagner <gw*****@agricoreunited.com>
comp.lang.javascript FAQ - http://jibbering.com/faq

Jul 23 '05 #9
Grant Wagner <gw*****@agricoreunited.com> wrote in message news:<41***************@agricoreunited.com>...
I wasn't aware you were referring to server-side JavaScript under BroadVision. Yes, I've seen BroadVision return
an object that can not be converted to a string. I can't remember the specific circumstances, nor what I did to
resolve it. However, you have to be aware of circumstances when you are returning BVI_ objects and when you are
returning JavaScript objects. For example:

// returns a BVI_Value object:
var aBviValueObject = aBviTable.get(0, "column_name");
// which you should access using:
Response.write(aBviValueObject.stringValue);


This would indeed fit into the context where my function is actually called!

Do you see a way to check at runtime what type an object actually is,
or wheather it contains a toString method?

Ronald
Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: praba kar | last post by:
Dear All, I have doubt regarding date string to time conversion function. In Python I cannot find flexible date string conversion function like php strtotime. I try to use following type...
10
by: Carl Gilbert | last post by:
Hi I am working on a site to provide displaying and navigation of images from several groups and have the following code that changes to displayed gif based on the query string passed in: ...
5
by: Cogito | last post by:
In a form I have two text fields. In one of them the user enters a decimal number and in the other a hexadecimal number. What code can be used to validate that the entered text is numeric and to...
4
by: Ross | last post by:
Anyone have some code to help me understand how I can convert a given hex string, say "0009dbaa00004c00000000fb82ca621c," into a struct of this form: struct uniqueid { ulong32_t word1;...
12
by: ABeck | last post by:
Hello List, I have ar more or less academical question. Can there arise runtime errors in a program, if the include of <string.h> has been forgotten? If all the arguments to the functions of...
72
by: Jacob | last post by:
I have compiled a set og unit testing recommendations based on my own experience on the concept. Feedback and suggestions for improvements are appreciated: ...
6
by: tommaso.gastaldi | last post by:
Hi, does anybody know a speedy analog of IsNumeric() to check for strings/chars. I would like to check if an Object can be treated as a string before using a Cstr(), clearly avoiding the time...
4
by: Russell Warren | last post by:
I've got a case where I want to convert binary blocks of data (various ctypes objects) to base64 strings. The conversion calls in the base64 module expect strings as input, so right now I'm...
30
by: Alf P. Steinbach | last post by:
I once suggested in that SomeOne Else(TM) should propose a string value class that accepted literals and char pointers and so on, with possible custom deleter, and in case of literal strings just...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.