English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial di base JavaScript

Oggetto JavaScript

Funzione JavaScript

JS HTML DOM

BOM del browser JS

Tutorial di base AJAX

Manuale di riferimento JavaScript

Metodi delle Stringhe JavaScript

Nell'ultimo capitolo abbiamo imparato le basi delle stringhe, ora diamo un passo avanti e consideriamo alcune operazioni utili che possiamo eseguire sulle stringhe con metodi e proprietà integrati.

I valori originali (ad esempio “New Delhi”) non possono avere proprietà o metodi (poiché non sono oggetti).

Ma nel JavaScript, i metodi e le proprietà possono essere utilizzati anche per i valori originali, perché il JavaScript considera i valori originali come oggetti quando esegue metodi e proprietà.

Ricerca della lunghezza della stringa

lunghezzaL'attributo restituisce la lunghezza della stringa. Per una stringa vuota, la lunghezza è 0.

var str = 'Java Script';
str.length;// return 11
Prova a vedere‹/›

Attenzione:Lo spazio è considerato come un carattere:

Metodo concat()

concat()Il metodo serve per connettere due o più stringhe.

var a = 'w3codebox';
var b = 'COM';
var c = a.concat(b);
Prova a vedere‹/›

Attenzione:Tutti i metodi di stringa restituiscono un nuovo valore. Non modificano la variabile originale.

Convertire in maiuscolo o minuscolo

toUpperCase()Il metodo restituisce il valore della stringa chiamata convertito in maiuscolo.

var str1 = "oldtoolbag.com";
var str2 = str1.toUpperCase();
Prova a vedere‹/›

toLowerCase()Il metodo restituisce il valore della stringa chiamata convertito in minuscolo.

var str1 = "oldtoolbag.com";
var str2 = str1.toLowerCase();
Prova a vedere‹/›

Trova una sottostringa nella stringa

indexOf()Il metodo restituisce la posizione della prima occorrenza di un valore specificato nella stringa (indice).

var str = 'Air Pollution is introduction of chemicals to the atmosphere';
str.indexOf('Pollution');// 4
Prova a vedere‹/›

Attenzione:L'indice del primo carattere è 0, l'indice del secondo carattere è 1, ecc.

lastIndexOf()Il metodo restituisce la posizione dell'ultima occorrenza di un valore specificato nella stringa (indice).

var str = 'Hello world, I repeat Hello world';
str.lastIndexOf('Hello');// 22
Prova a vedere‹/›

indexOf()ConlastIndexOf()Restituisce-1Se il valore non è trovato:

var str = "oldtoolbag.com";
str.indexOf("fish");
str.lastIndexOf("beer");
Prova a vedere‹/›

indexOf()ConlastIndexOf()Tutti accettano un secondo parametro come posizione di partenza della ricerca:

var str = 'HELLO WORLD HELLO';
str.indexOf('L', 6);
Prova a vedere‹/›

Cerca una sottostringa nella stringa

search()Il metodo esegue una ricerca per trovare corrispondenze tra l'espressione regolare e la stringa.

Se trova una corrispondenza, restituirà la posizione della prima corrispondenza, se non trova corrispondenze, restituirà-1:

var str = 'The question is to be, or not to be, that is to be.';
var pos = str.search('to be');
Prova a vedere‹/›

Esempio seguente dimostra l'uso dell'espressione regolare con il segno 'i' (ignora maiuscole e minuscole):

var str = 'The question is TO BE, or not to be, that is to be.';
var pos = str.search(/to be/i);
Prova a vedere‹/›

Più avanti in questo tutorial, imparerai di più sulle espressioni regolari.

Convert string to array

split()The method splits the string into an array of substrings and returns the new array.

We will usesplit()The method separates the array by spaces represented by the character " ".

var str = 'can you help me?';
var arr = str.split(" ");
Prova a vedere‹/›

Now we arearrAn array has been added to the variable, and we can access each element using the index number:

arr[0];        // Air
arr[2];        // is
Prova a vedere‹/›

In the following example, we will use "i" as a delimiter:

var str = 'can you help me?';
var arr = str.split("i");
Prova a vedere‹/›

If an empty string ("") is used as a delimiter, the string will be converted to a character array:

var str = 'can you help me?';
var arr = str.split(
Prova a vedere‹/›

By splitting the string, you can determine how many words are in a sentence.

Remove spaces before and after the string

trim()The method removes spaces from both ends of the string but cannot remove spaces between strings, spaces can be tabs or spaces.

var greeting = "         Hello world!         ";
greeting.trim();
Prova a vedere‹/›

This is a common simple method to perform deletion of extra spaces.

Replace string value

replace()The method returns a new string that has part or all of the pattern matches and is replaced by the replacement.

The first parameter will be the value to find, and the second parameter will be the value to replace it with.

var str1 = 'The question is to be, or not to be, that is to be.';
var str2 = str1.replace('to be', 'ZZZ');
Prova a vedere‹/›

By default, the replace() method only replaces the first match.

To replace all occurrences, please use a regular expression with the g flag (global search):

var str1 = 'The question is to be, or not to be, that is to be.';
var str2 = str1.replace(/to be/g, 'ZZZ');
Prova a vedere‹/›

To replace case-insensitive code, please use a regular expression with the i flag (ignore case):

var str1 = 'The question is TO BE, or not to be, that is to be.';
var str2 = str1.replace(/to be/gi, 'ZZZ');
Prova a vedere‹/›

Più avanti in questo tutorial, imparerai di più sulle espressioni regolari.

Estrazione di una parte della stringa

Ci sono tre metodi per estrarre una parte della stringa:

Metodo slice()

slice()Il metodo estrae una parte della stringa e la restituisce come nuova stringa senza modificare la stringa originale.

Questo metodo ha due parametri:Inizio dell'indice (start)eFine dell'indice (end)(non inclusaFine)。

Questo esempio estrae una parte della stringa dall'indice 3 all'indice 9 (10-1):

var str = 'Hello Javascript oldtoolbag.com';
var ext = str.slice(3, 10);
Prova a vedere‹/›

Attenzione:L'indice del primo carattere è 0, l'indice del secondo carattere è 1, ecc.

Scegliere dalla fine della stringa utilizzando indici negativi:

var str = 'Hello Javascript oldtoolbag.com';
var ext = str.slice(-8, -3);
Prova a vedere‹/›

Se si omette il secondo parametro, questa metodo taglierà il resto della stringa:

var str = 'Hello Javascript oldtoolbag.com';
var ext = str.slice(3);
Prova a vedere‹/›

Esempio seguente utilizza slice() per estrarre l'ultimo carattere:

var str = 'Hello Javascript oldtoolbag.com';
var ext = str.slice(-1);
Prova a vedere‹/›

metodo substring()

substring()Il metodo è simile aslice()Metodo

La differenza sta nelsubstring()Non accetta indici negativi.

var str1 = 'can you help me?';
var str2 = str1.substring(4, 10);
Prova a vedere‹/›

Se si omette il secondo parametro, allorasubstring()Il metodo estrarrà il resto della stringa:

var str1 = 'can you help me?';
var str2 = str1.substring(7);
Prova a vedere‹/›

metodo substr()

substr()Il metodo è simile aslice()Metodo

La differenza sta nel secondo parametro che specifica la parte da estrarre:Lunghezza.

Esempi seguenti sono usati persubstr()Estrae i caratteri dall'indice 4, della lunghezza 18:

var str1 = 'can you help me?';
var str2 = str1.substr(4, 18);
Prova a vedere‹/›

Se si omette il secondo parametro, allorasubstr()Il metodo estrarrà il resto della stringa:

var str1 = 'can you help me?';
var str2 = str1.substr(7);
Prova a vedere‹/›

Per estrarre caratteri dalla fine della stringa, utilizzare gli indici negativi:

var str1 = 'Hello Javascript oldtoolbag.com';
var str2 = str1.substr(-6, 3); // tor
Prova a vedere‹/›

Accedi ai caratteri delle stringhe

Ci sono tre metodi per accedere ai caratteri delle stringhe:

Metodo charAt()

charAt()Il metodo restituisce il carattere specificato all'indice indicato.

var str = 'Hello Javascript oldtoolbag.com';
str.charAt(1); // Restituisce a
Prova a vedere‹/›

Esempio di sotto: restituisce l'ultimo carattere della stringa:

var str = 'Hello Javascript oldtoolbag.com';
str.charAt(str.length-1);
Prova a vedere‹/›

Metodo charCodeAt()

charCodeAt()Il metodo restituisce un intero compreso tra 0 e 65535, che rappresenta il codice unità UTF-16 dell'indice fornito.

var str = 'Hello Javascript oldtoolbag.com';
str.charCodeAt(1); // Restituisce 97
Prova a vedere‹/›

Notazione di parentesi quadri[]

Puoi usare la notazione di parentesi quadri [] per restituire qualsiasi carattere della stringa[].

All'interno degli parentesi quadri, includere l'indice del carattere da restituire.

var str = 'Hello Javascript oldtoolbag.com';
str[0]; // Restituisce P
str[1]; // Restituisce a
Prova a vedere‹/›

Completo Riferimento Stringa

Per una riferimento completo delle proprietà e delle metodologie, visitare il nostroRiferimento Stringa JavaScript.

La parte di riferimento contiene descrizioni e esempi di tutte le proprietà e le metodologie di stringa.