473,382 Members | 1,353 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,382 software developers and data experts.

str.replace

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
12 4007
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
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
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
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
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
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
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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Craig Keightley | last post by:
Can these lines of sql statements be consolidated into one sql statement (possibly using reg exps??) BEGIN CODE ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Update...
12
by: Barnes | last post by:
Does anyone know of a good way to use the JavaScript string.replace() method in an ASP form? Here is the scenario: I have a form that cannot accept apostrophes. I want to use the replace() so...
6
by: Danny | last post by:
I need an asp command to strip out from a string all extra punctuation such as apostrophe, comma, period, spaces dashes, etc etc and just leave the letters. Can anybody give me some ideas? ...
9
by: Peter Row | last post by:
Hi, I know this has been asked before, but reading the threads it is still not entirely clear. Deciding which .Replace( ) to use when. Typically if I create a string in a loop I always use a...
4
by: Cor | last post by:
Hi Newsgroup, I have given an answer in this newsgroup about a "Replace". There came an answer on that I did not understand, so I have done some tests. I got the idea that someone said,...
3
by: Goran Djuranovic | last post by:
Hi all, I ran into a problem where my XMLTextReader fails on .Read() when I have "<" character in one of the attribute's values. What I am trying to do is replace illegal characters ("<", "&" ,...
3
by: TOXiC | last post by:
Hi everyone, First I say that I serched and tryed everything but I cannot figure out how I can do it. I want to open a a file (not necessary a txt) and find and replace a string. I can do it...
6
by: JackpipE | last post by:
Here is my replace query and I need to run this on every column in my table. Right now I manually enter the column name (_LANGUAGES_SPOKEN) but this is time consuming and would like to automate...
5
by: V S Rawat | last post by:
I was trying to use back-to-back replace functions to convert a url: str1 = str.replace("%2F","/").replace("%3F","?").replace("%3D","=").replace("%2 6","&"); It didn't replace all 4 types of...
15
by: =?Utf-8?B?TWlrZSAiWU9fQkVFIiBC?= | last post by:
I have a text file that contains about 8 to 10 text sequences that I need to replace. I want to search and replace all 8 to 10 text sequence anytime I run this script Here is what I have so...
1
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: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.