473,395 Members | 2,468 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,395 software developers and data experts.

string.seach() RegEx question

If I am trying to find an expression, foo, I can do something like
this:

rExp = /foo/gi;
if(results.search(rExp) > -1){

and all work fine.

however, if I want my search term to be a variable, bar:
var bar= "foo";
i get error when I try to concatinate bar into the regex.

I'm not very good with Regular expressions, or JavaScript for that
matter, but apparently rExp is not a string or it would be in quotes,
and it isn't an integer or boolean. So what is it's data type? and how
would I merge the variable bar into it so that it is /bar/gi?

Thanks,
L^K
Jul 20 '05 #1
11 1849
Lord Khaos wrote on 16 dec 2003 in comp.lang.javascript:
If I am trying to find an expression, foo, I can do something like
this:

rExp = /foo/gi;
if(results.search(rExp) > -1){

and all work fine.

however, if I want my search term to be a variable, bar:
var bar= "foo";
i get error when I try to concatinate bar into the regex.

I'm not very good with Regular expressions, or JavaScript for that
matter, but apparently rExp is not a string or it would be in quotes,
and it isn't an integer or boolean. So what is it's data type? and how
would I merge the variable bar into it so that it is /bar/gi?

<script>
function TestDemo(teststr, s){
re = new RegExp(teststr,"gi");
return re.test(s);
};

bar = "foo";
alert( TestDemo(bar, "foobar") );
</script>
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jul 20 '05 #2
Lord Khaos wrote:
If I am trying to find an expression, foo, I can do something like
this:

rExp = /foo/gi;
if(results.search(rExp) > -1){

and all work fine.

however, if I want my search term to be a variable, bar:
var bar= "foo";
i get error when I try to concatinate bar into the regex.

I'm not very good with Regular expressions, or JavaScript for that
matter, but apparently rExp is not a string or it would be in quotes,
and it isn't an integer or boolean. So what is it's data type? and how
would I merge the variable bar into it so that it is /bar/gi?

Thanks,
L^K


var bar = "foo";
var rExp = new RegExp(bar, "gi");
var results = "blah blah foo blah";
if (results.search(rExp) > -1) {
// Please note:
// "if (rExp.test(results)) {"
// is faster if all you're doing is testing for a match
// and you don't care about the resulting matches
// it also works when results is null
alert("yes");
}

Also note that if [bar] is going to contain any special regex entities
(\d, \s, etc), you need to apply string character escaping rules to them:

var bar = "\d"; // this regex will find a digit right?
var rExp = new RegExp(bar);
var result = "1";
alert(rExp.test(result)); // hmm, it's false

var bar = "\\d"; // no, this will find a single digit
var rExp = new RegExp(bar);
var result = "1";
alert(rExp.test(result)); // now it's true like it's supposed to be

If you're setting [bar] in a loop, you can avoid creating a new object
each time by using the compile() method:

var rExp = new RegExp();
for (var i = 0; i < loop.length; i++) {
rExp.compile(yourArray[i]);
if (rExp.test(result)) {
// ...
}

--
| Grant Wagner <gw*****@agricoreunited.com>

* Client-side Javascript and Netscape 4 DOM Reference available at:
*
http://devedge.netscape.com/library/...ce/frames.html

* Internet Explorer DOM Reference available at:
*
http://msdn.microsoft.com/workshop/a...ence_entry.asp

* Netscape 6/7 DOM Reference available at:
* http://www.mozilla.org/docs/dom/domref/
* Tips for upgrading JavaScript for Netscape 7 / Mozilla
* http://www.mozilla.org/docs/web-deve...upgrade_2.html
Jul 20 '05 #3
Thank you both for the help, that is just what I was looking for- I
think ??? :)

What I'm actually doing is trying to write ASP/JavaScript where the
user enters a search term into a form. I have the following:
=========================
<% @Language="JavaScript" %>
<!-- #include file="dsnless_db.inc" -->
<%
var search= Request.QueryString("term");
var my_ids = new Array();
var i=0;
sql="select name, description, id from products";
RS=Connection.Execute(sql);
rExp = new RegExp(search, "gi");
do{
results = RS.Fields("description").value;
results2= RS.Fields("name").value;
if(results.search(rExp) > -1 || results2.search(rExp) > -1){
my_ids[i]=RS.Fields("id").value;
i++}
RS.MoveNext;
}while(!RS.EOF);

var number = my_ids.length;
if(number > 0){ %>
<html><body>
<%
for(i=0;i<number;i++){
sql="SELECT * FROM products WHERE id=" + my_ids[i];
RS=Connection.Execute(sql);%>
<%
do{ %><b>Product #
<%Response.write(RS.Fields("id"));%>
</b><P>
<br><% Response.write(RS.Fields("name")); %>
<br>
<% Response.write(RS.Fields("description"));
%>
<br><% Response.write(RS.Fields("price")); %>
<hr></P>
<% RS.MoveNext;
}while(!RS.EOF);
}
}
Connection.Close ;

%>
------------------------
This works, thank you again, but I'm wondering now if .test would be
better than search.

TIA,
L^K
Jul 20 '05 #4
Lord Khaos <lo*******@comcast.net> wrote in
news:eq********************************@4ax.com:
If I am trying to find an expression, foo, I can do something like
this:

rExp = /foo/gi;
if(results.search(rExp) > -1){

and all work fine.

however, if I want my search term to be a variable, bar:
var bar= "foo";
i get error when I try to concatinate bar into the regex.

I'm not very good with Regular expressions, or JavaScript for that
matter, but apparently rExp is not a string or it would be in quotes,
and it isn't an integer or boolean. So what is it's data type? and how
would I merge the variable bar into it so that it is /bar/gi?


Its data type (class) is RegExp. You can create one from a string by using
the RegExp constructor: rExp=new RegExp(bar,"gi");

or, since you might want to match whatever is in bar only if it appears as
a single word (i.e. match "foo" but not "football"), you can use a string
expression as the first argument: rExp=new RegExp("\\b"+bar+"\\b","gi");

Note that when you're building a RegExp from a string, you have to escape
any backslashes in string literals that you want to become metacharacters,
and you have to double-escape any backslashes that you want to become
literal match characters. If the argument above had been "\b"+bar+"\b"
then the string expression would evaluate to a backspace character followed
by the contents of bar followed by another backspace character and the
regexp would be created from that, which is not what you want.
Jul 20 '05 #5
Grant Wagner <gw*****@agricoreunited.com> wrote in
news:3F***************@agricoreunited.com:
If you're setting [bar] in a loop, you can avoid creating a new object
each time by using the compile() method:

var rExp = new RegExp();
for (var i = 0; i < loop.length; i++) {
rExp.compile(yourArray[i]);
if (rExp.test(result)) {
// ...
}


How widely supported is this? I don't see any mention of it in Flanagan or
the Netscape core reference.
Jul 20 '05 #6
Eric Bohlman <eb******@earthlink.net> writes:

[rExp.compile]
How widely supported is this? I don't see any mention of it in Flanagan or
the Netscape core reference.


Not widely, I would have thought. It's not part of ECMAScript either.

However, a quick test shows it supported by Mozilla Firebird, Opera 5+,
IE 6, and Netscape 4. That's very wide already.

(and not Netscape 3 (no RegExp at all) or Opera 4 (appears to accept
/a/ syntax, but doesn't do anything with it))

/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 20 '05 #7
Lasse Reichstein Nielsen wrote:
Eric Bohlman <eb******@earthlink.net> writes:

[rExp.compile]
How widely supported is this? I don't see any mention of it in Flanagan or
the Netscape core reference.


Not widely, I would have thought. It's not part of ECMAScript either.

However, a quick test shows it supported by Mozilla Firebird, Opera 5+,
IE 6, and Netscape 4. That's very wide already.

(and not Netscape 3 (no RegExp at all) or Opera 4 (appears to accept
/a/ syntax, but doesn't do anything with it))

/L


It's been available since JavaScript 1.2 in Netscape:

<url:
http://devedge.netscape.com/library/...p.html#1194687
/>
<url:
http://devedge.netscape.com/library/...p.html#1194687
/>

Although oddly enough, the compile() method isn't listed in JavaScript 1.5, and I
haven't noticed until now because I typically use the 1.3 documentation to avoid
any temptation to do anything Netscape 4.7x won't understand. What's even
stranger is there is no mention made of the dropping of the compile() method, and
indicates that (as does the documentation above) that the RegExp() object has
been available since JavaScript 1.2.

<url:
http://msdn.microsoft.com/library/en...asp?frame=true
/> indicates that the compile() method has been available in JScript since
Version 3 (Internet Explorer 4).

I'm surprised it isn't part of ECMAScript, since it obviously provides a
performance advantage over having to create a new RegExp() object everytime you
want to evaluate a new pattern, as in the loop example.

--
| Grant Wagner <gw*****@agricoreunited.com>

* Client-side Javascript and Netscape 4 DOM Reference available at:
*
http://devedge.netscape.com/library/...ce/frames.html

* Internet Explorer DOM Reference available at:
*
http://msdn.microsoft.com/workshop/a...ence_entry.asp

* Netscape 6/7 DOM Reference available at:
* http://www.mozilla.org/docs/dom/domref/
* Tips for upgrading JavaScript for Netscape 7 / Mozilla
* http://www.mozilla.org/docs/web-deve...upgrade_2.html
Jul 20 '05 #8
JRS: In article <ll**********@hotpop.com>, seen in
news:comp.lang.javascript, Lasse Reichstein Nielsen <lr*@hotpop.com>
posted at Tue, 16 Dec 2003 23:43:23 :-

However, a quick test shows it supported by Mozilla Firebird, Opera 5+,
IE 6, and Netscape 4. That's very wide already.


And MSIE 4, apparently

The small Flanagan book has it, without specific version warning;
overall, RegExp is "Core Javascript 1.2".

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> Jsc maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/Jsc/&c, FAQ topics, links.
Jul 20 '05 #9
Eric Bohlman wrote:
Lord Khaos <lo*******@comcast.net> wrote in
news:eq********************************@4ax.com:


It is called `attribution _line_'.
[...]
and it isn't an integer or boolean. So what is it's data type? and how
would I merge the variable bar into it so that it is /bar/gi?


Its data type (class) is RegExp. [...]


Its data type is `object'. It is an instance of the RegExp object,
meaning that this object is contained in its prototype chain. More,
it is a RegExp object since it was created using the RegExp(...)
constructor function (called implicitly here through the literal
notation). There are no classes in JavaScript 1.x because it is a
prototype-based language, not a class-based one.
PointedEars
Jul 20 '05 #10
Thomas 'PointedEars' Lahn <Po*********@web.de> writes:
Eric Bohlman wrote:
Lord Khaos <lo*******@comcast.net> wrote in
news:eq********************************@4ax.com:


It is called `attribution _line_'.


No. Son-of-RFC-1036 speaks only of "attribution lines".
No RFC says anything (try an RFC-search for "attribution").

What SoRFC-1026 says (Section 4.3.2, Body Convetions):
---
Some followup agents supply "attribution" lines for quoted context,
indicating where it first appeared and under whose name. When
multiple levels of quoting are present and quoted context is edited
for brevity, "inner" attribution lines are not always retained. The
editing process is also somewhat error-prone. Reading agents (and
readers) are warned not to assume that attributions are accurate.

UNRESOLVED ISSUE: Should a standard format for attribution lines
be defined? There is already considerable diversity... but
automatic news analysis would be substantially aided by a standard
convention.
---
(plus a reference to attribution lines in section 10.2)

Alas, a standard format for attribution line*s* has not been defined.

/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 20 '05 #11
JRS: In article <3F**************@PointedEars.de>, seen in
news:comp.lang.javascript, Thomas 'PointedEars' Lahn
<Po*********@web.de> posted at Sat, 27 Dec 2003 01:45:51 :-
Eric Bohlman wrote:
Lord Khaos <lo*******@comcast.net> wrote in
news:eq********************************@4ax.com:


It is called `attribution _line_'.


Ignore this would-be dictator.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 20 '05 #12

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

Similar topics

10
by: Hank Kingwood | last post by:
This is probably an easy question, but I can't find a function (maybe my syntax is off...) to search for in a string. If someone would help out, I'd appreciate it! Also, how would you...
2
by: Tim Conner | last post by:
Hi, Thanks to Peter, Chris and Steven who answered my previous answer about regex to split a string. Actually, it was as easy as create a regex with the pattern "/*-+()," and most of my string...
32
by: tshad | last post by:
Can you do a search for more that one string in another string? Something like: someString.IndexOf("something1","something2","something3",0) or would you have to do something like: if...
2
by: Dan Schumm | last post by:
I'm relatively new to regular expressions and was looking for some help on a problem that I need to solve. Basically, given an HTML string, I need to highlight certain words within the text of the...
17
by: Tom | last post by:
Is there such a thing as a CONTAINS for a string variable in VB.NET? For instance, I want to do something like the following: If strTest Contains ("A","B", "C") Then Debug.WriteLine("Found...
7
by: Brian Mitchell | last post by:
Is there an easy way to pull a date/time stamp from a string? The DateTime stamp is located in different parts of each string and the DateTime stamp could be in different formats (mm/dd/yy or...
4
by: Chris | last post by:
Hi Everyone, I am using a regex to check for a string. When all the file contains is my test string the regex returns a match, but when I embed the test string in the middle of a text file a...
15
by: morleyc | last post by:
Hi, i would like to remove a number of characters from my string (\t \r \n which are throughout the string), i know regex can do this but i have no idea how. Any pointers much appreciated. Chris
4
by: tonywh00t | last post by:
Hi everyone, I have a "simple" question, especially for people familiar with regex. I need to parse strings that have the form: 1:3::5:9 which indicates the set of integers {1 3 4 5 9}. In...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.