[thelist] regex help

Kelly Hallman khallman at wrack.org
Tue Sep 2 23:56:57 CDT 2003


On Tue, 2 Sep 2003, Tom Dell'Aringa wrote:
> var stuRegEx = /[s]/;
> var students = thisData.split(stuRegEx);
> for(var t=0;t<=students.length; t++) {
>   if(students[t] == studentID.substring(1,2)) {	
>     students[t] = null; } }
> 
> for(var q=0;q<=students.length; q++)
> { if(students[q]){
>   students[q] = "s" + students[q];
>   thisDataField.value += students[q]; } }

This could be simplified into one loop, yeah?

var stuRegEx = /s/;
var students = thisData.split(stuRegEx);
for(var t=0;t<=students.length; t++) {
  if(students[t] != studentID.substring(1,2)) {
    result += students[t]; } }

Or, what I think you wanted to originally do, with a regex replace:

stringvar = 's1s23s234s462s342';
stripvar  = '23';
regex = new RegExp('s'+stripvar+'s');

stringvar += 's'; // add an extra s onto the end
stringvar  = stringvar.replace(re,'s');
stringvar  = stringvar.substring(0,(stringvar.length)-1);

So, the way you create a regex with a variable in it is to use the RegExp
constructor. Using var regex = /xyz/; is shorthand for creating a RegExp
object, but you can't use a variable since it's a special construct.

Consider the regex /s23/ and you can see why it needs to be /s23s/ ..  
Replacing '' on /s23/ would turn 's234s343' into 's4s343' (ugh). So my
solution to that was to append an s on the end, match /s###s/ and replace
with an 's', then strip the last 's' off the end after the replace.

As for why you are storing and manipulating your data this way, I will
assume you have your reasons and refrain from asking the 'why' :)

Two final notes: you used a regex /[s]/ above to do your split -- this is
equivalent to the regex /s/ ... also, it needn't be a regex if it's that
simple; the split method will also work with a string: myvar.split('s')

-- 
Kelly Hallman
http://wrack.org/





More information about the thelist mailing list