473,320 Members | 1,848 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.

RegExp to alter an element name?

VK
Hello!

Given a string like
<input type="button" name="b1" value="Button">

I want to locate the element's name (b1) and replace it with this very name
+ some spice.

And of course it can be any kind of loose HTML syntacs:
name="b1"
NAME="b1"
name='b1'
NAME=b1
....

So it's something like (totally wrong expression, I know):
/name=(s+|'|")(name)/$1+my_spice/i

But I did not work with regexp for a longest time, and I'm just too lazy
(sorry to admit) to read manuals over again just for one case.
Any Samaritan soul around here?


Jul 23 '05 #1
7 1414
On Sat, 27 Nov 2004 16:07:26 +0100, VK <sc**********@yahoo.com> wrote:
Given a string like <input type="button" name="b1" value="Button">

I want to locate the element's name (b1) and replace it with this very
name + some spice.

And of course it can be any kind of loose HTML syntacs:
name="b1"
NAME="b1"
name='b1'
NAME=b1
...


Try:

str = str.replace(
/(name=)([\"\']?)([\w.:-]+|[^\"]+|[^\']+)\2/i,
'$1$2$3' + stuff + '$2'
);

where 'str' is your string, and 'stuff' is your spice [sic]. I've given it
a quick test, and it appears to handle everything you want it to. There
might be a simpler option, though.

By the way, it will accept value with and without both kinds of quotes,
but if quotes are omitted, the value must conform to the Specification.
That is, only letters, numbers, underscores (_), periods (.), colons (:),
and hyphens (-) will be accepted.

[snip]

Good luck,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #2
VK
THANK YOU!
Jul 23 '05 #3
On Sat, 27 Nov 2004 15:56:24 GMT, Michael Winter
<M.******@blueyonder.co.invalid> wrote:

[snip]
str = str.replace(
/(name=)([\"\']?)([\w.:-]+|[^\"]+|[^\']+)\2/i,
'$1$2$3' + stuff + '$2'
);
I just realised that I've reintroduced a problem I initially removed. With
the regular expression above, the second saved match contains either a
quote character, or nothing if the attribute value wasn't quoted in the
first place. When the replacement string is constructed, the result of
this match - a quote or nothing - will be used again, which means that as
it stands, the 'stuff' string would have to conform to the same
restrictions as unquoted values:

[snip]
That is, only letters, numbers, underscores (_), periods (.), colons
(:), and hyphens (-) will be accepted.


Presumably, you're taking a string obtained from innerHTML, modifying it,
and placing it back into the document. That would account for the leniency
you wanted as different browsers normalise the innerHTML string in
different ways.

If the restriction I unintentionally imposed is unacceptable, one way
around it is to use a function, rather than a string, with
String.prototype.replace:

var stuff = '...';
function addStuff() {
var s = arguments[2] || '"';
return arguments[1] + s + arguments[3] + stuff + s;
}

str = str.replace(
/(name=)([\"\']?)([\w.:-]+|[^\"]+|[^\']+)\2/i,
addStuff
);

The only problem here is that IE only supports a function argument with
JScript 5.5+ (IE 5.5+/WinME/WinXP). Though a toString method could be
defined which performs the original operation:

addStuff.toString = function() {
return '$1$2$3' + stuff + '$2';
};

IE normalises its innerHTML strings so that unnecessary quotes are removed
- back to square one.

If you do reach this point, you'll have to abandon my suggestion. The last
recourse would be the String.prototype.split method, however IE's
implementation is broken[1] when used with regular expressions.

Mike
[1] Well, it doesn't conform to ECMA-262, 3rd Ed.

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #4
VK
It may help I guess if I explain what am I doing.

I'm finishing my European vacations next week (irrelevant to JavaScript,
just to start the speech :-)
I want to make a .js library to handle tables dynamically (add/remove/clone
rows, attach the behaviors to cells etc.)

The OP's RegExp was a part of my method to clone rows in IE tables (under
TOM).
As IE doesn't allow to operate on the ROW level (you have to go cell by
cell), for rows cloning within the same table, I did:

for (i=0;oldRow.cells.length;i++) {
var oCell = newRow.insertCell();
oCell.innerHTML = oldRow.cells[i].innerHTML;
}

The problem pops up if we have an enclosing form with form elements inside
the cloning cells. Obviously the cloned row will contain the cloned form
elements as well with the same names.
I thought the simplest fix would be to use a RegExp to alter the source
element name before pass it to the target?
Jul 23 '05 #5
On Mon, 29 Nov 2004 14:55:00 +0100, VK <sc**********@yahoo.com> wrote:

[snip]
As IE doesn't allow to operate on the ROW level (you have to go cell by
cell), for rows cloning within the same table, I did:


[snip]

An alternative approach could be to clone the row with the Node.cloneNode
method. Something like:

var newRow = rowParent.cloneNode(true),
newInputs = newRow.getElementsByTagName('INPUT');
for(var i = 0, n = newInputs.length; i < n; ++i) {
newInputs[i].name = /* ... */;
}
rowParent.appendChild(newRow);

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #6
"Michael Winter" <M.******@blueyonder.co.invalid> wrote in message news:<opsicptae1x13kvk@atlantis>...
On Mon, 29 Nov 2004 14:55:00 +0100, VK <sc**********@yahoo.com> wrote:

[snip]
As IE doesn't allow to operate on the ROW level (you have to go cell by
cell), for rows cloning within the same table, I did:
[snip]

An alternative approach could be to clone the row with the Node.cloneNode
method. Something like:

var newRow = rowParent.cloneNode(true),
newInputs = newRow.getElementsByTagName('INPUT');
for(var i = 0, n = newInputs.length; i < n; ++i) {
newInputs[i].name = /* ... */;
}
rowParent.appendChild(newRow);

Mike


On another thread, R Cornford wrote:
RobB wrote:
<snip>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
lang="en">
<head> <snip>
var alldivs = document.getElementsByTagName('DIV');

<snip>

XHTML DOMs are case sensitive (like XHTML mark-up) and because the tag
and attribute names are all lowercase in the mark-up they are expected
to also be all lowercase when being referred to with scripts. Additionally, the namespace qualified ('NS' prefixed) methods (when
available) produce more reliable results in XHTML DOMs. Richard.
I noticed MW used:
newInputs = newRow.getElementsByTagName('INPUT');


....and would appreciate their insight into this issue. I've always -
until recently - used lower-case tagnames, making comparisons with
DOM-returned strings using case-insensitive regexes to avoid browser
differences. However I've noticed numerous experienced programmers
utilizing upper-case tagnames as parameters to DOM methods. Why?
Jul 23 '05 #7
RobB wrote:
Michael Winter wrote:
newInputs = newRow.getElementsByTagName('INPUT'); <snip>
On another thread, R Cornford wrote:

<snip> XHTML DOMs are case sensitive (like XHTML mark-up) and
because the tag and attribute names are all lowercase
in the mark-up they are expected to also be all lowercase
when being referred to with scripts.

Additionally, the namespace qualified ('NS' prefixed)
methods (when available) produce more reliable results
in XHTML DOMs.


I noticed MW used:
newInputs = newRow.getElementsByTagName('INPUT');


...and would appreciate their insight into this issue.
I've always - until recently - used lower-case tagnames,
making comparisons with DOM-returned strings using
case-insensitive regexes to avoid browser differences.
However I've noticed numerous experienced programmers
utilizing upper-case tagnames as parameters to DOM methods.
Why?


The difference between an HTML DOM, which is case insensitive
(theoretically) and in which tagName properties are upper-case, and an
XHTML DOM, which is case sensitive and has lower case tag names (that
may additionally be namespace qualified).

When Mike posts mark-up it is HTML (usually HTML 4.01 strict), so it is
an HTML DOM that he is expecting to be scripting. When you post mark-up
it is invariably XHTML, and so logic would suggest that it is the XHTML
DOM that you intend to be scripting.

Richard.
Jul 23 '05 #8

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

Similar topics

3
by: Martin Lucas-Smith | last post by:
Can anyone point me to a regular expression in PHP which could be used to check that a proposed (My)SQL database/table/column name is valid, i.e. shouldn't result in an SQL error when created? ...
5
by: Lukas Holcik | last post by:
Hi everyone! How can I simply search text for regexps (lets say <a href="(.*?)">(.*?)</a>) and save all URLs(1) and link contents(2) in a dictionary { name : URL}? In a single pass if it could....
0
by: Chris Croughton | last post by:
I'm trying to use the EXSLT regexp package from http://www.exslt.org/regexp/functions/match/index.html (specifically the match function) with the libxml xltproc (which supports EXSLT), but...
10
by: BuddhaBuddy | last post by:
Platform is DB2/NT 7.2.9 The table was created like this: CREATE TABLE MYTEST ( MYTESTOID bigint not null primary key, FK_OTHEROID bigint not null references other, FK_ANOTHEROID bigint not...
4
by: Jeff Kish | last post by:
Hi. I have a database I need to supply something (I'm assuming a t-sql script.. maybe something else is better) to update customer tables with. The operations include mostly changing varchar...
6
by: Christoph | last post by:
I'm trying to set up client side validation for a textarea form element to ensure that the data entered does not exceed 200 characters. I'm using the following code but it doesn't seem to be...
7
by: Csaba Gabor | last post by:
I need to come up with a function function regExpPos (text, re, parenNum) { ... } that will return the position within text of RegExp.$parenNum if there is a match, and -1 otherwise. For...
9
by: =?ISO-8859-1?Q?BJ=F6rn_Lindqvist?= | last post by:
With regexps you can search for strings matching it. For example, given the regexp: "foobar\d\d\d". "foobar123" would match. I want to do the reverse, from a regexp generate all strings that could...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
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
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
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: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
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...
1
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.