String length String slice() String substring() String substr() String replace() String replaceAll() String toUpperCase() String toLowerCase() String concat() String trim() String trimStart() String trimEnd() String padStart() String padEnd() String charAt() String charCodeAt() String split()
String søgning metoder er dækket i næste kapitel.
Egenskaben length
returnerer længden af en streng:
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The length Property</h2>
<p>The length of the string is:</p>
<p id="demo"></p>
<script>
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.getElementById("demo").innerHTML = text.length;
</script>
</body>
</html>
Der er 3 metoder til at udtrække en del af en streng:
slice(start, end)
substring(start, end)
substr(start, length)
slice()
udtrækker en del af en streng og returnerer udtrukket del i en ny streng.
Metoden tager 2 parametre: startposition og slutposition (slut ikke inkluderet).
Skær en del af en snor ud fra position 7 til position 13:
let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13);
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The slice() Method</h2>
<p>The sliced (extracted) part of the string is:</p>
<p id="demo"></p>
<script>
let text = "Apple, Banana, Kiwi";
let part = text.slice(7,13);
document.getElementById("demo").innerHTML = part;
</script>
</body>
</html>
JavaScript tæller positioner fra nul.
Første position er 0.
Anden position er 1.
Hvis du udelader den anden parameter, vil metoden skære resten af strengen ud:
let text = "Apple, Banana, Kiwi";
let part = text.slice(7);
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The slice() Method</h2>
<p>Extract a part of a string from position 7:</p>
<p id="demo"></p>
<script>
let text = "Apple, Banana, Kiwi";
let part = text.slice(7)
document.getElementById("demo").innerHTML = part;
</script>
</body>
</html>
Hvis en parameter er negativ, tælles positionen fra slutningen af strengen:
let text = "Apple, Banana, Kiwi";
let part = text.slice(-12);
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The slice() Method</h2>
<p>Extract a part of a string counting from the end:</p>
<p id="demo"></p>
<script>
let text = "Apple, Banana, Kiwi";
let part = text.slice(-12);
document.getElementById("demo").innerHTML = part;
</script>
</body>
</html>
Dette eksempel skærer en del af en streng ud fra position -12 til position -6:
let text = "Apple, Banana, Kiwi";
let part = text.slice(-12, -6);
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The slice() Method</h2>
<p>Extract a part of a string and return the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
let text = "Apple, Banana, Kiwi";
let part = text.slice(-12,-6)
document.getElementById("demo").innerHTML = part;
</script>
</body>
</html>
substring()
ligner slice()
.
Forskellen er, at start- og slutværdier mindre end 0 behandles som 0 tommer understreng()
.
let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>The substring() method extract a part of a string and returns the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.substring(7,13);
</script>
</body>
</html>
Hvis du udelader den anden parameter, vil substring()
skære resten af snor.
substr()
ligner slice()
.
Forskellen er at den anden parameter angiver længden af den udtrukne del.
let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>The substr() method extract a part of a string
and returns the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.substr(7,6);
</script>
</body>
</html>
Hvis du udelader den anden parameter, vil substr()
skære resten af snor.
let str = "Apple, Banana, Kiwi";
let part = str.substr(7);
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>The substr() method extract a part of a string and returns the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.substr(7);
</script>
</body>
</html>
Hvis den første parameter er negativ, tæller positionen fra slutningen af snor.
let str = "Apple, Banana, Kiwi";
let part = str.substr(-4);
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>The substr() method extract a part of a string and returns the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.substr(-4);
</script>
</body>
</html>
Metoden replace()
erstatter en specificeret værdi med en anden værdi i en streng:
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.replace("Microsoft","W3Schools");
}
</script>
</body>
</html>
Metoden replace()
ændrer ikke den streng, den kaldes på.
Metoden replace()
returnerer en ny streng.
Metoden replace()
erstatter kun det første match
Hvis du vil erstatte alle matches, skal du bruge et regulært udtryk med /g-flagsættet. Se eksempler nedenfor.
Som standard erstatter metoden replace()
kun det første match:
let text = "Please visit Microsoft and Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft and Microsoft!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.replace("Microsoft","W3Schools");
}
</script>
</body>
</html>
Som standard skelnes der mellem store og små bogstaver i replace()
-metoden. Skriver MICROSOFT (med store bogstaver) vil ikke virke:
let text = "Please visit Microsoft!";
let newText = text.replace("MICROSOFT", "W3Schools");
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>Try to replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.replace("MICROSOFT","W3Schools");
}
</script>
<p>The replace() method is case sensitive. MICROSOFT (with upper-case) will not be replaced.</p>
</body>
</html>
For at erstatte store og små bogstaver, brug et regulært udtryk med et /i
flag (ufølsomt):
let text = "Please visit Microsoft!";
let newText = text.replace(/MICROSOFT/i, "W3Schools");
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.replace(/MICROSOFT/i,"W3Schools");
}
</script>
</body>
</html>
Regelmæssige udtryk skrives uden anførselstegn.
For at erstatte alle matches skal du bruge et regulært udtryk med et /g
flag (globalt match):
let text = "Please visit Microsoft and Microsoft!";
let newText = text.replace(/Microsoft/g, "W3Schools");
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>Replace all occurrences of "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft and Microsoft!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.replace(/Microsoft/g,"W3Schools");
}
</script>
</body>
</html>
Du vil lære meget mere om regulære udtryk i kapitlet JavaScript Regular Udtryk.
I 2021 introducerede JavaScript strengmetoden replaceAll()
:
text = text.replaceAll("Cats","Dogs");
text = text.replaceAll("cats","dogs");
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The replaceAll() Method</h2>
<p>ES2021 intoduced the string method replaceAll().</p>
<p id="demo"></p>
<script>
let text = "I love cats. Cats are very easy to love. Cats are very popular."
text = text.replaceAll("Cats","Dogs");
text = text.replaceAll("cats","dogs");
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Metoden replaceAll()
giver dig mulighed for at angive en regulært udtryk i stedet for en streng, der skal erstattes.
Hvis parameteren er et regulært udtryk, skal det globale flag (g) ellers indstilles en TypeError vises.
text = text.replaceAll(/Cats/g,"Dogs");
text = text.replaceAll(/cats/g,"dogs");
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The replaceAll() Method</h2>
<p>ES2021 intoduced the string method replaceAll().</p>
<p id="demo"></p>
<script>
let text = "I love cats. Cats are very easy to love. Cats are very popular";
text = text.replaceAll(/Cats/g,"Dogs");
text = text.replaceAll(/cats/g,"dogs");
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
replaceAll()
er en ES2021-funktion.
replaceAll()
virker ikke i Internet Explorer.
En streng konverteres til store bogstaver med toUpperCase()
:
En streng konverteres til små bogstaver med toLowerCase()
:
let text1 = "Hello World!";
let text2 = text1.toUpperCase();
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>Convert string to upper case:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Hello World!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.toUpperCase();
}
</script>
</body>
</html>
let text1 = "Hello World!"; // String
let text2 = text1.toLowerCase(); // text2 is text1
converted to lower
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>Convert string to lower case:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Hello World!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.toLowerCase();
}
</script>
</body>
</html>
concat()
forbinder to eller flere strenge:
let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String</h1>
<h2>The concat() Method</h2>
<p>The concat() method joins two or more strings:</p>
<p id="demo"></p>
<script>
let text1 = "Hello";
let text2 = "World!";
let text3 = text1.concat(" ",text2);
document.getElementById("demo").innerHTML = text3;
</script>
</body>
</html>
Metoden concat()
kan bruges i stedet for plusoperatoren. Disse to linjer gør det samme:
text = "Hello" + " " + "World!";
text = "Hello".concat(" ", "World!");
Alle strengmetoder returnerer en ny streng. De ændrer ikke den originale streng.
Formelt sagt:
Strenge er uforanderlige: Strenge kan ikke ændres, kun erstattes.
Metoden trim()
fjerner mellemrum fra begge sider af en streng:
let text1 = " Hello World! ";
let text2 = text1.trim();
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The trim() Method</h2>
<p id="demo"></p>
<script>
let text1 = " Hello World! ";
let text2 = text1.trim();
document.getElementById("demo").innerHTML =
"Length text1 = " + text1.length + "<br>Length text2 = " + text2.length;
</script>
</body>
</html>
ECMAScript 2019 føjede strengmetoden trimStart()
til JavaScript. <p>trimStart()
-metoden fungerer som trim()
, men fjerner kun mellemrum fra starten af en snor.
let text1 = " Hello World! ";
let text2 = text1.trimStart();
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The trimStart() Method</h2>
<p id="demo"></p>
<script>
let text1 = " Hello World! ";
let text2 = text1.trimStart();
document.getElementById("demo").innerHTML =
"Length text1 = " + text1.length + "<br>Length text2 = " + text2.length;
</script>
</body>
</html>
JavaScript-strengen trimStart()
er understøttet i alle moderne browsere siden januar 2020:
Chrome 66 | Edge 79 | Firefox 61 | Safari 12 | Opera 50 |
Apr 2018 | Jan 2020 | Jun 2018 | Sep 2018 | May 2018 |
ECMAScript 2019 føjede strengmetoden trimEnd()
til JavaScript. <p>trimEnd()
-metoden fungerer som trim()
, men fjerner kun mellemrum fra slutningen af en snor.
let text1 = " Hello World! ";
let text2 = text1.trimEnd();
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The trimEnd() Method</h2>
<p id="demo"></p>
<script>
let text1 = " Hello World! ";
let text2 = text1.trimEnd();
document.getElementById("demo").innerHTML =
"Length text1 = " + text1.length + "<br>Length text2 = " + text2.length;
</script>
</body>
</html>
JavaScript-strengen trimEnd()
er understøttet i alle moderne browsere siden januar 2020:
Chrome 66 | Edge 79 | Firefox 61 | Safari 12 | Opera 50 |
Apr 2018 | Jan 2020 | Jun 2018 | Sep 2018 | May 2018 |
ECMAScript 2017 føjede to nye strengmetoder til JavaScript: padStart()
og padEnd()
for at understøtte udfyldning i begyndelsen og slutningen af en streng.
Metoden padStart()
udfylder en streng fra starten.
Den puder en streng med en anden streng (flere gange), indtil den når en given længde.
Pad en streng med "0", indtil den når længden 4:
let text = "5";
let padded = text.padStart(4,"0");
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The padStart() Method</h2>
<p>The padStart() method pads a string from the start.</p>
<p>It pads the string with another string (multiple times) until it reaches a given length.</p>
<p id="demo"></p>
<script>
let text = "5";
text = text.padStart(4,"0");
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Pad en streng med "x", indtil den når længden 4:
let text = "5";
let padded = text.padStart(4,"x");
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The padStart() Method</h2>
<p>The padStart() method pads a string from the start.</p>
<p>It pads the string with another string (multiple times) until it reaches a given length.</p>
<p id="demo"></p>
<script>
let text = "5";
document.getElementById("demo").innerHTML = text.padStart(4,"x");
</script>
</body>
</html>
Metoden padStart()
er en strengmetode.
For at udfylde et tal skal du først konvertere tallet til en streng.
Se eksemplet nedenfor.
let numb = 5;
let text = numb.toString();
let padded = text.padStart(4,"0");
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The padStart() Method</h2>
<p>The padStart() method pads a string from the start.</p>
<p>It pads the string with another string (multiple times) until it reaches a given length.</p>
<p id="demo"></p>
<script>
let numb = 5;
let text = numb.toString();
document.getElementById("demo").innerHTML = text.padStart(4,0);
</script>
</body>
</html>
padStart()
er en ECMAScript 2017-funktion.
Det understøttes i alle moderne browsere:
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
padStart()
understøttes ikke i Internet Explorer.
Metoden padEnd()
udfylder en streng fra enden.
Den puder en streng med en anden streng (flere gange), indtil den når en given længde.
let text = "5";
let padded = text.padEnd(4,"0");
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The padEnd() Method</h2>
<p>The padEnd() method pads a string at the end.</p>
<p>It pads the string with another string (multiple times) until it reaches a given length.</p>
<p id="demo"></p>
<script>
let text = "5";
text = text.padEnd(4,"0");
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
let text = "5";
let padded = text.padEnd(4,"x");
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The padEnd() Method</h2>
<p>The padEnd() method pads a string at the end.</p>
<p>It pads the string with another string (multiple times) until it reaches a given length.</p>
<p id="demo"></p>
<script>
let text = "5";
document.getElementById("demo").innerHTML = text.padEnd(4,"x");
</script>
</body>
</html>
Metoden padEnd()
er en strengmetode.
For at udfylde et tal skal du først konvertere tallet til en streng.
Se eksemplet nedenfor.
let numb = 5;
let text = numb.toString();
let padded = text.padEnd(4,"0");
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The padEnd() Method</h2>
<p>The padEnd() method pads a string at the end.</p>
<p>It pads the string with another string (multiple times) until it reaches a given length.</p>
<p id="demo"></p>
<script>
let numb = 5;
let text = numb.toString();
document.getElementById("demo").innerHTML = text.padEnd(4,"x");
</script>
</body>
</html>
padEnd()
er en ECMAScript 2017-funktion.
Det understøttes i alle moderne browsere:
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
padEnd()
understøttes ikke i Internet Explorer.
Der er 3 metoder til at udtrække strengtegn:
charAt(position)
charCodeAt(position)
Ejendomsadgang [ ]
Metoden charAt()
returnerer tegnet ved en specificeret indeks (position) i en streng:
let text = "HELLO WORLD";
let char = text.charAt(0);
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String</h1>
<h2>The charAt() Method</h2>
<p>The charAt() method returns the character at a given position in a string:</p>
<p id="demo"></p>
<script>
var text = "HELLO WORLD";
document.getElementById("demo").innerHTML = text.charAt(0);
</script>
</body>
</html>
Metoden charCodeAt()
returnerer tegnets unicode ved et specificeret indeks i en streng:
Metoden returnerer en UTF-16-kode (et heltal mellem 0 og 65535).
let text = "HELLO WORLD";
let char = text.charCodeAt(0);
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String</h1>
<h2>The charCodeAt() Method</h2>
<p>The charCodeAt() method returns the unicode of the character at a given position in a string:</p>
<p id="demo"></p>
<script>
let text = "HELLO WORLD";
document.getElementById("demo").innerHTML = text.charCodeAt(0);
</script>
</body>
</html>
ECMAScript 5 (2009) tillader egenskabsadgang [ ] på strenge:
let text = "HELLO WORLD";
let char = text[0];
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<p>Property access on strings:</p>
<p>The first character in the string is:</p>
<p id="demo"></p>
<script>
let text = "HELLO WORLD";
document.getElementById("demo").innerHTML = text[0];
</script>
</body>
</html>
Ejendomsadgang kan være lidt uforudsigelig:
Det får strenge til at ligne arrays (men det er de ikke)
Hvis der ikke findes noget tegn, returnerer [ ] udefineret, mens charAt() returnerer en tom streng.
Den læses kun. str[0]="A" giver ingen fejl (men virker ikke!)
let text = "HELLO WORLD";
text[0] = "A"; // Gives no error, but does not work
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<p>Property acces on strings are read only:</p>
<p id="demo"></p>
<script>
let text = "HELLO WORLD";
text[0] = "A"; // Does not work
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Hvis du vil arbejde med en streng som et array, kan du konvertere det til et array.
En streng kan konverteres til en matrix med split()
metoden:
text.split(",") // Split on commas
text.split(" ") // Split on spaces
text.split("|") // Split on pipe
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>Display the first array element, after a string split:</p>
<p id="demo"></p>
<script>
let text = "a,b,c,d,e,f";
const myArray = text.split(",");
document.getElementById("demo").innerHTML = myArray[0];
</script>
</body>
</html>
Hvis separatoren udelades, vil det returnerede array indeholde hele strengen i indeks [0].
Hvis separatoren er "", vil den returnerede matrix være en matrix af enkelt tegn:
text.split("")
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<h2>The split().Method</h2>
<p id="demo"></p>
<script>
let text = "Hello";
const myArr = text.split("");
text = "";
for (let i = 0; i < myArr.length; i++) {
text += myArr[i] + "<br>"
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
For en komplet strengreference, gå til vores:
Komplet JavaScript-strengreference.
Referencen indeholder beskrivelser og eksempler på alle strengegenskaber og metoder.