By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,139 Members | 1,897 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,139 IT Pros & Developers. It's quick & easy.

str.replace

P: n/a
I want to use regxp to check that a form input contains at least 1
non-space charcter. I'd like to only run this if the browser supports
it. For DOM stuff, I'd use

if (documentGetElementById) {}

Is there an object/feature detection I can use to check for regxp string
manipulation support?

--
Brian (remove ".invalid" to email me)
http://www.tsmchughs.com/
Jul 23 '05 #1
Share this Question
Share on Google+
12 Replies


P: n/a
On Sun, 15 Aug 2004 11:40:30 -0400, Brian
<us*****@julietremblay.com.invalid> wrote:
I want to use regxp to check that a form input contains at least 1
non-space charcter. I'd like to only run this if the browsersupports it.
For DOM stuff, I'd use

if (documentGetElementById) {}
You mean

if(document.getElementById) ...
Is there an object/feature detection I can use to check for regxpstring
manipulation support?


There's no need. Regular expressions have existed in JavaScript since v1.2
(NN4). The only thing you do need to test is that more recent additions to
the available constructs (lookahead matches and the like) are supported.

Hope that helps,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail
Jul 23 '05 #2

P: n/a
Brian wrote:
I want to use regxp to check that a form input contains at least 1
non-space charcter. I'd like to only run this if the browser supports
it. For DOM stuff, I'd use

if (documentGetElementById) {}
Assuming you mean:-

if (document.getElementById) {}

- it would be reckless to infer any level of DOM support (especially
dynamic DOM support) form that test. The only valid deduction available
form that test is that the browser supports - document.getElementById -
(useful to know if you intend using it but not the whole picture).

Is there an object/feature detection I can use to check for
regxp string manipulation support?


As your subjuect implies an interest in the string - replace - method:-

if(
(typeof String == 'function') &&
(String.prototype) &&
(String.prototype.replace)
){
... // String.prototype.replace is available.
}

Though realistically you can expect to have a - replace - method
available on all browser javascript implementations currently in use
(still, no harm in making sure).

The capabilities of String.prototype.replace might be additionally
tested with:-

<URL:
http://jibbering.com/faq/faq_notes/n...html#bdReplace >

Unfortunately jibbering.com appears to be unavailable at present so this
is the code used in that page:-

/* The original string is the one letter string literal "a". The
Regular Expression /a/ identifies that entire string, so it is the
entire original string that will be replaced. The second argument is
the function expression - function(){return ''';} -, so the entire
original string will be replaced with an empty string if the
function expression is executed. If it is instead type-converted
into a string that string will not be an empty string. The NOT (!)
operation type-converts its operand to boolean and then inverts it
so the results of the test is boolean true if function references
are supported in the second argument for the - replace - method, and
false when not supported:
*/
if(!('a'.replace(/a/, (function(){return '';})))){
... //function references OK.
}else{
... //no function references with replace.
}

If you want different, or more specific, regular expression testing then
the nature of the real problem defines the appropriate test and you have
not yet elucidated the real circumstances/problem.

Richard.
Jul 23 '05 #3

P: n/a
On Sun, 15 Aug 2004 17:30:02 +0100, "Richard Cornford"
<Ri*****@litotes.demon.co.uk> wrote:
Brian wrote:
<URL:
http://jibbering.com/faq/faq_notes/n...html#bdReplace >

Unfortunately jibbering.com appears to be unavailable at present so this
is the code used in that page:-


I won't go into the details why it's deaf, but I'm not happy a
bunny... hopefully back sometime in the afternoon of monday UK time.

Apologies everyone!

Jim.
Jul 23 '05 #4

P: n/a
Michael Winter wrote:
Brian wrote:
Is there an object/feature detection I can use to check for
regxpstring manipulation support?
There's no need. Regular expressions have existed in JavaScript since
v1.2 (NN4).


I'll defer to you on this, though it does make me nervous. I hate the
idea of unleasing any js without some sort of check first.
The only thing you do need to test is that more recent additions to
the available constructs (lookahead matches and the like) are
supported.


I'd be using something fairly simple (I think!), for onSubmit:

strTrimmed = str.replace(/\s+/g, '');
if (strTrimmed == "") {
// user tried to submit empty search query --
// insert error message in page or alert error
return false;
}

--
Brian (remove ".invalid" to email me)
http://www.tsmchughs.com/
Jul 23 '05 #5

P: n/a
Richard Cornford wrote:
Brian wrote:
I want to use regxp to check that a form input contains at least 1
non-space charcter. I'd like to only run this if the browser
supports it. For DOM stuff, I'd use

if (documentGetElementById) {}
Assuming you mean:-

if (document.getElementById) {}


I did; apologies for not editing more carefully.
- it would be reckless to infer any level of DOM support (especially
dynamic DOM support) form that test.
In the interest of keeping my post short, I erred on the side of
concise. When I'm doing anything dynamic with a document, I try to find
each method I'll use and test for that, e.g.,

if (document.getElementsByTagName && document.createElement &&
document.createTextNode) {}

Since this Usenet, I should have been a little more thorough, if only to
avoid misleading others.
Is there an object/feature detection I can use to check for regxp
string manipulation support?


if(
(typeof String == 'function') &&
(String.prototype) &&
(String.prototype.replace)
){
... // String.prototype.replace is available.
}

Thanks for that. I'm still learning, so it'll take a bit of time for me
to work through it. I've seen "typeof" comparisons, but I'm not sure
what they mean.

Aside: one of the challenges with learning JavaScript is that there
seems to be more bad advice on the web than good, so a simple Google
search does not always help.
Though realistically you can expect to have a - replace - method
available on all browser javascript implementations currently in use
(still, no harm in making sure).
ISTR that older browsers handle js errors rather crudely, but I cannot
be sure. Nor can I say whether it makes sense to fuss about IE 3.x or NN
3.x.
Unfortunately jibbering.com appears to be unavailable at present
I noticed that during research for this question; I was in fact trying
to read the faq.
/* The original string is the one letter string literal "a". The
Regular Expression /a/ identifies that entire string, so it is the
entire original string that will be replaced. The second argument is
the function expression - function(){return ''';} - [snip]

Yikes, I'm afraid that's a bit out of my league, but I've copied your
entire message for future reference.
If you want different, or more specific, regular expression testing
then the nature of the real problem defines the appropriate test and
you have not yet elucidated the real circumstances/problem.


I read this article yesterday:

http://www.adaptivepath.com/publicat...ves/000341.php

Point 3 suggested using js to help users avoid sending an empty string
to a site search. I thought that was a good idea, and pretty easy to do,
so I started writing a script. Then I thought that it would be nice to
also check for a string of only whitespace as well as an empty string.

In short: I have a site search form. Onsubmit, I want to strip all white
space from an text input field, then see if there are any characters
left. If there are not, I want to tell the user about the problem and
return false.

--
Brian (remove ".invalid" to email me)
http://www.tsmchughs.com/
Jul 23 '05 #6

P: n/a
Brian wrote:
I have a site search form. Onsubmit, I want to strip all white
space from an text input field, then see if there are any characters
left.


It just occurred to me that I should be able to simply look for a
non-whitespace character:

s = /.*\S.*/;
if (!s.test(str)) {
// warn user and return false
}

Have I missed something obvious?

--
Brian (remove ".invalid" to email me)
http://www.tsmchughs.com/
Jul 23 '05 #7

P: n/a
Brian <us*****@julietremblay.com.invalid> writes:
It just occurred to me that I should be able to simply look for a
non-whitespace character:

s = /.*\S.*/;
if (!s.test(str)) { .... Have I missed something obvious?

If you don't anchor the RegExp (with "^" and "$") then it matches
anywhere in the string, so ".*" isn't necessary:

var s = /\S/;

Otherwise fine.
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #8

P: n/a
On Sun, 15 Aug 2004 15:18:59 -0400, Brian
<us*****@julietremblay.com.invalid> wrote:

[regexp support is common]
I'll defer to you on this, though it does make me nervous. I hatethe
idea of unleasing any js without some sort of check first.
I think it would be pretty reckless for any browser to ignore support for
regular expressions. It's also part of the core language, so conforming
implementations must provide them.

If you wanted to check for the RegExp host object, you could try:

/* Get a reference to the global object,
* parent to built-in objects. */
var global = this;

if('function' == typeof global['RegExp'] &&
RegExp.prototype &&
RegExp.<name of function> )
{
// <name of function> supported
}

Yes, this is somewhat nabbed from Richard's post, however, I think that
it's prudent to not access the RegExp identifier directly in case it's not
provided (however unlikely that might be). If accessed directly by name:

if(RegExp) {

but not present, it will cause an error. If accessed as a property of an
object, it will simply evaluate to undefined.

With regard to using typeof, everything is represented by some form of
object. The various basic types are: undefined, null, boolean, number,
string, and object. When the typeof operator is used with one of these
types, it evaluates to a string that contains one of the following values:

Type Result
--------------------------------
Undefined "undefined"
Null "object"
Boolean "boolean"
Number "number"
String "string"
Object (native and "object"
doesn't implement
[[Call]])
Object (native and "function"
implements [[Call]])
Object (host) Implementation-dependent

This could be used for various purposes:

- Checking that a property is implemented

Unlike methods, you can't just use

if(object.property) {
// property implemented - doesn't work!

because the property could be one of many values that evaluate to false.
Instead, you use the typeof operator to distinguish the results:

if('undefined' != typeof object.property) {
// property implemented

- Overloading methods

In other languages, you can specify methods with the same name, but a
different signature; different arguments types. As JavaScript is
loosely-typed, this isn't possible in the same way. However, you can use
typeof to effect the same behaviour.

function useObject(o) {
/* If o is a string, use some method to obtain an
* appropriate object reference. */
if('string' == typeof o) {
o = getRef(o);
}
/* Check that o is now an object
* and that it's not null. */
if(o && 'object' == typeof o) {

There are bound to be other possibilities, but I lost my train of thought
after watching TV. :)

[snip]
strTrimmed = str.replace(/\s+/g, '');
if (strTrimmed == "") {
// user tried to submit empty search query --
// insert error message in page or alert error
return false;
}


Simpler still would be:

if(!/\S+/.test(str)) {
return false;
}

The regular expression, \S+, matches any string that contains one or more
non-whitespace characters.

Hope that helps,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail
Jul 23 '05 #9

P: n/a
Lasse Reichstein Nielsen wrote:
Brian writes:
s = /.*\S.*/;

If you don't anchor the RegExp (with "^" and "$") then it matches
anywhere in the string, so ".*" isn't necessary:

var s = /\S/;


Even better! Thanks for your time.

--
Brian (remove ".invalid" to email me)
http://www.tsmchughs.com/
Jul 23 '05 #10

P: n/a
Michael Winter wrote:
<snip>
Yes, this is somewhat nabbed from Richard's post, however, I
think that it's prudent to not access the RegExp identifier
directly in case it's not provided (however unlikely that
might be). If accessed directly by name:

if(RegExp) {

but not present, it will cause an error. If accessed as a
property of an object, it will simply evaluate to undefined.

<snip>

In a type-converting test an unqualified identifier that is not resolved
as a named property of some object on the scope chain will result in an
error. However, - typeof - has an extra safety measure in its specified
algorithm:-

<quote cite="ECMA 262 3rd edition">
11.4.3 The typeof Operator

The production UnaryExpression: typeof UnaryExpression is evaluated as
follows:

1. Evaluate UnaryExpression.
2. If Type(Result(1)) is not Reference, go to step 4.
3. If GetBase(Result(1)) is null, return "undefined".
4. Call GetValue(Result(1)).
5. Return a string determined by type(Result(4)) according
to the following table:
[ ... table as quoted in previous post ]
</quote>

Identifier resolution (ECMA 262 3rd edition section 10.1.4) always
returns an Reference type, with an unresolved identifier returning a
Reference type with a null base object, so step 3 in the typeof
algorithm safely returns "undefined".

Richard.
Jul 23 '05 #11

P: n/a
On Sun, 15 Aug 2004 22:46:56 +0100, Richard Cornford
<Ri*****@litotes.demon.co.uk> wrote:

[snip]
In a type-converting test an unqualified identifier that is not resolved
as a named property of some object on the scope chain will result in an
error. However, - typeof - has an extra safety measure in its specified
algorithm:-


Thank you for that. I think it's fair to say I had no idea, despite
staring straight at what you quoted. I wouldn't have reached the same
conclusion anyway: my ability to comprehend ECMA-262 has drastically
improved, but I still know little of the low-level mechanics of the
language.

[snip]

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail
Jul 23 '05 #12

P: n/a
Michael Winter wrote:
I think it would be pretty reckless for any browser to ignore support
for regular expressions. It's also part of the core language, so
conforming implementations must provide them.
Good to know. My nervousness comes from a lack of experience in js, and
warnings from knowledeable hackers about object detection.
If you wanted to check for the RegExp host object, you could try:
[lots of useful info snipped]
Hope that helps


Quite a bit. Thanks to everyone who posted in this thread. I'm much
closer to my goal than I was 2 days ago. :-)

--
Brian (remove ".invalid" to email me)
http://www.tsmchughs.com/
Jul 23 '05 #13

This discussion thread is closed

Replies have been disabled for this discussion.