Titolo visibile
Ristoranti Italia
Ristoranti Lazio
Pizzerie Napoletane
Ricerca per Regione
Ricerca Avanzata
Cucina Estera
Cucina Regionale
Scuole Private
Giornali Online

In questa pagina spiego cosa sono le stringhe e fornisco una panoramica delle cose utili che ci si possono fare.

Quando scrivi in linguaggio JavaScript devi conoscere cosa sono le stringhe e come funzionano.

All'inizio parleremo delle basi delle stringhe. Date le differenze con altri linguaggi di programmazione e' necessario approfondire l'uso delle stringhe in Javascript. Alla fine saranno riportate i metodi e proprieta' piu' importanti delle stringhe.

Basi sulle Stringhe

Let's review the basics of strings.


When you declare and manipulate strings in JavaScript, always write them with single quotes ' or double quotes " around them. This tells the browser that it's dealing with a string. Don't mix up your quotes, if you start a string with a single quote and end it with a double quote, JavaScript doesn't understand what you mean. As a rule, I use single quotes ' because I've decided to use double quotes for HTML and single quotes for JavaScript. You can of course do this the other way around, but I advise you to make some such rule for yourself.

Let's introduce our two test strings that we'll use throughout this page:

var a = 'Hello world!'; var b = 'I am a JavaScript hacker.'

Now we have declared two variables, a and b and put strings in them. Having done this, we can start working with them. But first of all, a problem: suppose I'd written

var b = 'I'm a JavaScript hacker.';

This string has a single quote in it, so JavaScript thinks that the string ends, doesn't understand what comes next and gives error messages. So you need to escape the single quote, telling the browser to treat the quote as a character, and not as a command to end the string. This is done by placing a backslash \ before it:

var b = 'I\'m a JavaScript hacker.'

Note that you can put double quotes in the string without escaping them. After all, you've defined the single quotes as the beginning and end of the string, so

var b = 'I\'m a JavaScript "hacker".'

gives no problems. The double quotes are automatically treated as parts of the string, not as commands.

Pre-written functions

Now that you've defined the strings, you can start using them. For instance, you can append one string to another, you can take the second to fourth character of b and put them in the middle of string a, you can read out what the twelfth character of a is, how many characters b has, if there's a 'q' in them and many more things.

To do this, you can use some automatic functions that JavaScript assigns to each string. One of them is .length that gives the length of the string. So if you want to get the length of 'Hello world!' you can do:

var c = 'Hello world!'.length;

But above we put this string in the variable a. Thereby you make a a string, so it also has a length and this yields the same result:

var c = a.length;

The important thing is that you can use .length on any string: it's an automatic feature. You can read out the length of any string, whether JavaScript makes it for you (like location.href or document.title) or you have declared it yourself.
I give a list of common automatical methods and properties below.

Stringhe e Numeri

JavaScript is very relaxed about the difference between strings and numbers. Some programming languages require you to state if a variable is a number or a string before doing anything else with it. Not so in JavaScript. In fact you can even add up numbers and strings:

var c = a + 12;

Some programming languages would shut down in disgust when they encounter this line. After all, a is a string and 12 is a number. JavaScript, however, tries to solve the problem by assuming 12 is also a string. So c becomes

Hello world!12

So if you use + on a string and a number, JavaScript is going to make the number a string for you. Better still, if you need it you can treat numbers as strings or strings as numbers.

Conversely, if you apply mathematics to a string, JavaScript tries to make it a number. If the string cannot be interpreted as a number (because there are letters in it, for instance), JavaScript gives NaN (Not a Number).

Finally, JavaScript makes no reliable difference between integers and floating point variables.

Da Numero a Stringa

To convert a number to a string, do:

var c = (16 * 24)/49 + 12; d = c.toString();

Now you can use all methods of strings on d, while c still contains the number.

Da Stringa a Numero

If you want to change a string to a number, first make sure there are only the characters 0-9 in the string. What I always do is simply multiplying the string by 1.

var c = '1234'; d = c * 1;

Since multiplying assumes numbers, JavaScript makes the string a number, if possible. If that isn't possible, the result is NaN. Note that you cannot do

var c = '1234'; d = c + 0;

This would yield '12340' because JavaScript thinks the + means concatenate string, not add.

Metodi e Proprieta' delle Stringhe

So what can we do with strings? Here's a list of automatic JavaScript commands. The concatenation is a special case, but all other commands can be used on any string by doing stringname.command().

Concatenating strings (+)

First of all, you can concatenate strings, sew them together as it were:

document.write(a + b);


Hello world!I am a JavaScript hacker.

But of course you want a space between the two sentences. No problem. By doing

document.write(a + ' ' + b);

we concatenate three strings: a, ' ' (one space) and b and we get

Hello world! I am a JavaScript hacker.

You can even use numbers or calculations, like:

document.write (a + 3*3 + b);

Now we concatenate string a, then the result of 3*3, treated as a string for the occasion, and then b, which gives

Hello world!9I am a JavaScript hacker.

Watch out if you want to add numbers. This

document.write (a + 3+3 + b);

concatenates four strings: a, 3, 3 and b, because + in this context means concatenate strings, not add, and gives

Hello world!33I am a JavaScript hacker.

Use brackets if you want to add 3 and 3 before making the string.

document.write (a + (3+3) + b);

concatenates a, the result of 3+3 and b and gives

Hello world!6I am a JavaScript hacker. Funzione indexOf

One of the most widely used automatical methods is indexOf. Each character has an index number, giving its position in the string. Note that the first character has index 0, the second one index 1 etc. So the index of 'w' in string a is 6.

Using indexOf we can read out the index number of a character. Put the .indexOf('') behind the string name and put the character you're looking for between the quotes. This

var a = 'Hello world!'; document.write(a.indexOf('w'))

gives 6. If the same character occurs more than once, this method gives the first occurrence. So


gives 4 because that's the index of the first 'o' in the string.

You can also look for a combination of characters (This is of course also a string, but to prevent confusion I won't call it so). indexOf returns the position of the first character of the combination. So

document.write(a.indexOf('o w'))

also gives 4 because that's the index of the 'o'.

Furthermore it's possible to search for a character only after a certain index number. For instance, if you'd do


you get the index number of the first 'o' coming after the character with index 5 (= the space), so it would give 7.

Finally, if the character or combination is not present in the string, indexOf gives -1. This is actually the widest use of indexOf: seeing if a certain combination of characters is present. It's the core of the browser detect script. To see if the browser is Explorer, you take the string navigator.userAgent and see if it contains 'MSIE':

if (navigator.userAgent.indexOf('MSIE') !=-1) { do something for Explorer }

If the index number of 'MSIE' is not -1 (if 'MSIE' occurs anywhere in the string), the browser is Explorer.

Funzione lastIndexOf

There's also lastIndexOf which gives the last occurrence of the character or combination. It otherwise works exactly as indexOf. This

var b = 'I am a JavaScript hacker.' document.write(b.lastIndexOf('a'))

gives 19 because that's the index of the last 'a' in the string.

Funzione charAt

charAt() gives you the character at a certain position. For instance, when you do

var b = 'I am a JavaScript hacker.' document.write(b.charAt(5))

gives 'a', because that's the character at the sixth position (remember, first character is 0!).

Funzione length

length gives you the length of a string.

var b = 'I am a JavaScript hacker.' document.write(b.length)

gives 25. Note that the length is 1 more than the index number of the last character.

Funzione split

split() is a specialized method that you need sometimes. It allows you to split a string at the places of a certain character. You must put the result in an array, not in a simple variable. Let's split b on the spaces.

var b = 'I am a JavaScript hacker.' var temp = new Array(); temp = b.split(' ');

Now the string has been split into 5 strings that are placed in the array temp. The spaces themselves are gone.

temp[0] = 'I'; temp[1] = 'am'; temp[2] = 'a'; temp[3] = 'JavaScript'; temp[4] = 'hacker.'; Funzione substring

substring is used to take a part of a string. Syntax is substring(first_index,last_index). So for instance

var a = 'Hello world!'; document.write(a.substring(4,8));

gives 'o wo', from the first 'o' (index 4) to the second one (index 7) Note that the 'r' (index 8) is not part of this substring.

You can also do

var a = 'Hello world!'; document.write(a.substring(4));

This gives the whole string from the character with index 4 on: 'o world!'.

Funzione substr

There is also a method substr() that works slightly differently. Instead of the second number being an index number, it gives the number of characters. So


starts at the character with index 4 ('o') and then gives 8 characters, so the output is

o world!

Since substr() is not supported by the Version 3 browsers I never use it.

Funzione toLowerCase e toUpperCase

Finally two methods that you need sometimes: toLowerCase() puts the whole string in lower case, toUpperCase() puts the whole string in upper case.

var b = 'I am a JavaScript hacker.' document.write(b.toUpperCase())

Scritto il 22/03/2009 alle ore 07:00:00

Condividi su Facebook

Per Regione
Solo Pizzerie
Solo Internazionale
Solo Italiana
Per Tipo Cucina
Per Città nel Lazio
Segnala locale
Feed Rss
Segnala un errore
Aggiungi a preferiti
Imposta Homepage
Segnala un Sito
Indice Ricette
Questo sito e' un sito non commerciale e potrebbe riportare informazioni non aggiornate e/o non corrette. Leggi il disclaimer sottostante.

Lavoro |  Home |  Locali |  Info                   316157                 Disclaimer |  Portale |  Blog |  Ricette