473,396 Members | 2,050 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,396 developers and data experts.

String Handling Opportunities with split(), indexOf() and RegExp

Atli
5,058 Expert 4TB
The following small HowTo is a compilation of an original problem in getting some cookie-values through different methods of string-handling.

The original Problem was posted as follows:

Hi.

Thought I'd share with you a little problem I had.
Check out this code.

Expand|Select|Wrap|Line Numbers
  1. var ca = document.cookie.split(';');    
  2. var value = "";
  3.  
  4. for (var x = 0; x < ca.length; x++) {
  5.     if (ca[x].indexOf(name) == 0) {
  6.         var start  = ca[x].indexOf('=') + 1;
  7.         var length = ca[x].length - start;
  8.  
  9.         value = ca[x].substr(start, length);
  10.     }
  11. }
  12.  
This code basicly takes the entire document.cookie string and splits it at every ';' and then searches for the 'name' at the start of each one.

This worked fine in IE, but it failed in all other browsers I checked (Firefox, Opera, Netscape).

Turns out everybody except MS decided to but a space(ascii nr 32) before each part of the split command, wich made the indexOf return 1 in stead of 0.

Now I've got to ask.. WTF?!?

Anyways be carefull with the split command.

-- Atli Ţór
As you can see, there could have been a problem with the split-method. The following short article handles ways around this possible problem, that we couldn't reproduce, but someone may possibly encounter it too sometimes. If nothing else, the shown adaptations will be helpful in understanding how to retrieve cookie-values or handle string-values with different js-methods.

First we test the split-method, since Atli guessed it could have a problem:

The split-command works well in FF 2.0.0.9:

I've used the following code:

Expand|Select|Wrap|Line Numbers
  1. var val = 'a=1;b=2;c=3'
  2.  
  3. var arr = val.match(/[^;]+/g);
  4.  
  5. // arr is ["a=1", "b=2", "c=3"] now
  6.  
  7. arr = val.split(';');
  8.  
  9. // arr is ["a=1", "b=2", "c=3"] now
  10.  
so it works as expected and I simply used the regEx to show another way to create an array from the string 'val'. Both methods are equivalent.

Next I checked the indexOf code ... that worked as expected too:

Expand|Select|Wrap|Line Numbers
  1. // lets assume we want to alert the value of c
  2. var name = 'c';
  3.  
  4. for(var x = 0; x < arr.length; x++) {
  5.    if (arr[x].indexOf(name) == 0) {
  6.       var start = arr[x].indexOf('=') + 1;
  7.       var length = arr[x].length - start;
  8.  
  9.       var value = arr[x].substr(start, length);
  10.       alert(value);
  11.    }
  12. }
  13.  
but we may use the regEx here too:

Expand|Select|Wrap|Line Numbers
  1. for (var x = 0; x < arr.length; x++) {
  2.    if ((new RegExp('^' + name)).test(arr[x])) {
  3.       var value = arr[x].match(/[^=]+$/);
  4.       alert(value);
  5.    }
  6. }
so I couldn't find anything wrong with indexOf or split ... but we have options to work around their use in cases where there would be a problem :)

So now we found that the problem could be another one than with the split-method. Atli responded with:

The regEx trick will definitely come in handy.

Looking back at this now, I see that I only tested this problem using data from cookies. Knowing how loosely M$ follows standards, and how much they like being different than everybody else, I think it more likely that the problem is with the cookie data rather than the split command.

It could very well be that IE creates cookies in one white-space free string, while the other browsers add a space between values, thus causing there to be an extra space when I split it on every semi-colon.
So we could use the regExp again to handle that in case that would be the real problem:

Expand|Select|Wrap|Line Numbers
  1. var value = ' c=1';
  2. value = value.replace(/^\s+/, '');
  3.  
  4. // now value has 'c=1' assigned
  5.  
that simply would remove any whitespaces at start of a string-value.

Now acoder jumped in and brought us back to the original problem with providing a getCookie function derived from w3schools:

Expand|Select|Wrap|Line Numbers
  1. function getCookie(name) {
  2.   if (document.cookie.length > 0) {
  3.     start = document.cookie.indexOf (name + "=");
  4.     if (start != -1) {
  5.       start += name.length + 1;
  6.       end = document.cookie.indexOf(";",start);
  7.       if (end == -1) end = document.cookie.length;
  8.       return unescape(document.cookie.substring(start,end));
  9.     }
  10.   }
  11.   return "";
  12. }
[Adapted from W3Schools JavaScript Cookies]

So this HowTo is a little case study on how to encounter a problem and how we could workaround and/or come back to the basic-problem ... :) and it shows again that working on code together is much more efficient then doing it alone, since we could learn that problems may not be quite clear at the first look we always may find a way around one special code-usage and having an eye on the original problem is always an advantage :)
Dec 29 '06 #1
1 8340
acoder
16,027 Expert Mod 8TB
and it shows again that working on code together is much more efficient then doing it alone, since we could learn that problems may not be quite clear at the first look we always may find a way around one special code-usage and having an eye on the original problem is always an advantage :)
I agree. Sometimes, you can miss a basic error which someone else can pick up. Other times, someone may have a better idea to solve a problem.
Dec 6 '07 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Stu Cazzo | last post by:
I have the following: String myStringArray; String myString = "98 99 100"; I want to split up myString and put it into myStringArray. If I use this: myStringArray = myString.split(" "); it...
11
by: Sandfordc | last post by:
I have tried several time to do this but have been unsucessful. I tried something like: myFunction(charater) str=frm.s1.value sb1=str.substring(0,charater)...
4
by: Jason Gleason | last post by:
What's the most efficient way to get the number of occurences of a certain string in another string..for instance i'm using the following code right now... private int CharacterCounter(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...
35
by: Cor | last post by:
Hallo, I have promised Jay B yesterday to do some tests. The subject was a string evaluation that Jon had send in. Jay B was in doubt what was better because there was a discussion in the C#...
4
by: Roshawn | last post by:
Hi, I am retrieving a list of book titles from a web service. What I'd like to do is shorten the titles, if possible. For example, there is a book titled "Malicious Mobile Code: Virus...
2
by: Digital Fart | last post by:
following code would split a string "a != b" into 2 strings "a" and "b". but is there a way to know what seperator was used? string charSeparators = { "=", ">=", "<=" , "!=" }; string s1 =...
8
by: shapper | last post by:
Hello, I have a string which holds a text. Is it possible to create a substring which uses the first N words of that string? Thanks, Miguel
7
by: Tom de Neef | last post by:
I need to change one character at a known position in a string. In Pascal I would change the P's character of a string S into 'x' with S:='x'; In JavaScript I come no further than S =...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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: 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
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.