473,664 Members | 3,066 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1829
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 "convertibl e 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.******@bluey onder.co.invali d> wrote in message news:<opshnubpq 7x13kvk@atlanti s>...
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.******@bluey onder.co.invali d> wrote in message news:<opshnubpq 7x13kvk@atlanti s>...
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.c om" 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 [nsIDOMWindowInt ernal.alert]" nsresult: "0x80570009 (NS_ERROR_XPC_B AD_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*****@agrico reunited.com>
comp.lang.javas cript FAQ - http://jibbering.com/faq

Jul 23 '05 #6
"Michael Winter" <M.******@bluey onder.co.invali d> wrote in message news:<opshpws3x sx13kvk@atlanti s>...
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*****@agrico reunited.com> wrote in message news:<41******* ********@agrico reunited.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.c om" 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*****@agrico reunited.com> wrote in message news:<41******* ********@agrico reunited.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.c om" 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_nam e");
// which you should access using:
Response.write( aBviValueObject .stringValue);

However:

// returns a String:
aBviTable.curso r = 0;
var aString = aBviTable.colum n_name;
// which can be accessed simply by:
Response.write( aString);

--
Grant Wagner <gw*****@agrico reunited.com>
comp.lang.javas cript FAQ - http://jibbering.com/faq

Jul 23 '05 #9
Grant Wagner <gw*****@agrico reunited.com> wrote in message news:<41******* ********@agrico reunited.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_nam e");
// 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
3727
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 function 1) parsedate function failed if a date string like below format "16-MAY-2005 01:26" 2)parsedate_tz function also failed if a date string
10
1772
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: Call: <a href="ShowImage.asp?group=01&image=01&max=28">Group 01, Image 04,
5
1507
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 produce a warning when it is not.
4
6409
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; ulong32_t word2; ulong32_t word3; ulong32_t word4; };
12
2202
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 <string.h> are correct, is it possible that an error occurs, and what an error might this be? Regards
72
5230
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: http://geosoft.no/development/unittesting.html Thanks.
6
2202
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 and resource consuming Try... Catch, which in iterative processing is totally unacceptable. -tom
4
5530
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 converting the binary blocks to strings first, then converting the resulting string to base64. This seems highly inefficient and I'd like to just go straight from binary to a base64 string. Here is the conversion we're using from object to...
30
2453
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 carrying the original pointer. In other words, for the simplest usage code: * no overhead (just carrying a pointer or two), and * no possibility of exceptions (for that case).
0
8348
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8861
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
7375
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6187
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5660
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4351
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2764
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2003
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1759
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.