[ Web Proxy ]
URL:
Viewing: https://fa.javascript.info/string [Back]  [Original]

:
DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek

(string) . .

UTF-16 .

.

backtick :

let single = ' ';
let double = " ";

let backticks = `backtick`;

. backtick {...}$ :

function sum(a, b) {
  return a + b;
}

alert(`1 + 2 = ${sum(1, 2)}.`); // 1 + 2 = 3.

backtick :

let guestList = `:
 * John
 * Pete
 * Mary
`;

alert(guestList); //      

.

:

let guestList = "Guests: // Error: Unexpected token ILLEGAL
  * John";

. Backtick .

Backtick backtick . : func`string`. func . . . .

\n :

let guestList = ":\n * John\n * Pete\n * Mary";

alert(guestList); //         

:

let str1 = "Hello\nWorld"; // "      "  

// backtick         
let str2 = `Hello
World`;

alert(str1 == str2); // true

<<<<<<< HEAD :

There are other, less common special characters:

18b1314af4e0ead5a2b10bb4bacd24cecbb3f18e

<<<<<<< HEAD
\n
\r \r\n \n .
. \n .
\',\",\`
\\ Backslash
\t Tab
\b, \f, \v Backspace, Form Feed, Vertical Tab ( ).

backslash \ . (escape character) .

backslash \ :

alert( `The backslash: \\` ); // The backslash: \

escaped \' \" \` .

:

alert( 'I\'m the Walrus!' ); // I'm the Walrus!

backslash \ .

. backtick :

alert( "I'm the Walrus!" ); // I'm the Walrus!

<<<<<<< HEAD Unicode \u .

Besides these special characters, theres also a special notation for Unicode codes \u, its rarely used and is covered in the optional chapter about Unicode.

18b1314af4e0ead5a2b10bb4bacd24cecbb3f18e

length :

alert( `My\n`.length ); // 3

\n 3 .

length

str.length() str.length . .

<<<<<<< HEAD str.length . .

Please note that str.length is a numeric property, not a function. There is no need to add parenthesis after it. Not .length(), but .length.

18b1314af4e0ead5a2b10bb4bacd24cecbb3f18e

<<<<<<< HEAD pos str.charAt(pos) . :

To get a character at position pos, use square brackets [pos] or call the method str.at(pos). The first character starts from the zero position:

18b1314af4e0ead5a2b10bb4bacd24cecbb3f18e

let str = `Hello`;

//  
alert( str[0] ); // H
alert( str.at(0) ); // H

//  
alert( str[str.length - 1] ); // o
alert( str.at(-1) );

<<<<<<< HEAD charAt .

[] undefined charAt :

As you can see, the .at(pos) method has a benefit of allowing negative position. If pos is negative, then its counted from the end of the string.

So .at(-1) means the last character, and .at(-2) is the one before it, etc.

The square brackets always return undefined for negative indexes, for instance:

18b1314af4e0ead5a2b10bb4bacd24cecbb3f18e

let str = `Hello`;

<<<<<<< HEAD
alert( str[1000] ); // undefined
alert( str.charAt(1000) ); // '' (  )
=======
alert( str[-2] ); // undefined
alert( str.at(-2) ); // l
>>>>>>> 18b1314af4e0ead5a2b10bb4bacd24cecbb3f18e

for..of :

for (let char of "Hello") {
  alert(char); // H,e,l,l,o (  "l"  "e"  "H"  char)
}

. .

:

let str = 'Hi';

str[0] = 'h'; //  
alert( str[0] ); //  

str .

:

let str = 'Hi';

str = 'h' + str[1]; //    

alert( str ); // hi

.

toLowerCase() toUpperCase() :

alert( 'Interface'.toUpperCase() ); // INTERFACE
alert( 'Interface'.toLowerCase() ); // interface

:

alert( 'Interface'[0].toLowerCase() ); // 'i'

.

str.indexOf

str.indexOf(substr, pos) .

substr str pos -1 .

:

let str = 'Widget with id';

alert( str.indexOf('Widget') ); // 0      'Widget' 
alert( str.indexOf('widget') ); // -1           

alert( str.indexOf("id") ); // 1 ( id  ..idget)   1   "id"

.

"id" 1 . 2 :

let str = 'Widget with id';

alert( str.indexOf('id', 2) ) // 12

indexOf . :

let str = 'As sly as a fox, as strong as an ox';

let target = 'as'; //     

let pos = 0;
while (true) {
  let foundPos = str.indexOf(target, pos);
  if (foundPos == -1) break;

  alert( `Found at ${foundPos}` );
  pos = foundPos + 1; //       
}

:

let str = "As sly as a fox, as strong as an ox";
let target = "as";

let pos = -1;
while ((pos = str.indexOf(target, pos + 1)) != -1) {
  alert( pos );
}
str.lastIndexOf(substr, position)

indexOf if . if :

let str = "Widget with id";

if (str.indexOf("Widget")) {
    alert("We found it"); // ! 
}

alert str.indexOf("Widget") 0 ( ). if 0 false .

-1 :

let str = "Widget with id";

if (str.indexOf("Widget") != -1) {
    alert("We found it"); // !  
}

includes startsWith endsWith

str.includes(substr, pos) str substr true/false .

:

alert( "Widget with id".includes("Widget") ); // true

alert( "Hello".includes("Bye") ); // false

str.includes :

alert( "Widget".includes("id") ); // true
alert( "Widget".includes("id", 3) ); // false    "id"   3 

str.startsWith( ) str.endsWith( ) :

alert( "Widget".startsWith("Wid") ); // true    "Wid"  "Widget"
alert( "Widget".endsWith("get") ); // true    "get"  "Widget"

3 : substring substr slice.

str.slice(start [, end])

start end ( end ) .

:

let str = "stringify";
alert( str.slice(0, 5) ); // 'strin' :   0  5 ( 5 )
alert( str.slice(0, 1) ); // 's' : 0  1   1       0 

slice :

let str = "stringify";
alert( str.slice(2) ); // 'ringify' :    

start/end . :

let str = "stringify";

//   4        1     
alert( str.slice(-4, -1) ); // 'gif'
str.substring(start [, end])

start end ( end ).

slice start end ( start end ).

:

let str = "stringify";

//   substring   
alert( str.substring(2, 6) ); // "ring"
alert( str.substring(6, 2) ); // "ring"

// ...  slice  
alert( str.slice(2, 6) ); // "ring" ( )
alert( str.slice(6, 2) ); // "" (  )

( slice) 0 .

str.substr(start [, length])

start length () .

length () :

let str = "stringify";
alert( str.substr(2, 4) ); // 'ring' :   4   

:

let str = "stringify";
alert( str.substr(-4, 2) ); // 'gi' :   2   

:

slice(start, end) start end ( end )
substring(start, end) start end ( end ) 0
substr(start, length) start length start

. substr : Annex B . . .

slice .

slice .

() .

.

  1. :

    alert( 'a' > 'Z' ); // true
  2. :

    alert( 'sterreich' > 'Zealand' ); // true

    . Zealand sterreich .

<<<<<<< HEAD .

UTF-16 . : . .

To understand what happens, we should be aware that strings in Javascript are encoded using UTF-16. That is: each character has a corresponding numeric code.

There are special methods that allow to get the character for the code and back:

18b1314af4e0ead5a2b10bb4bacd24cecbb3f18e

str.codePointAt(pos)

pos :

//         
alert( "z".codePointAt(0) ); // 122

<<<<<<< HEAD alert( Z.codePointAt(0) ); // 90 alert( z.codePointAt(0).toString(16) ); // 7a ( )

alert( "z".codePointAt(0).toString(16) ); // 7a (if we need a hexadecimal value)

18b1314af4e0ead5a2b10bb4bacd24cecbb3f18e

```
String.fromCodePoint(code)

:

alert( String.fromCodePoint(90) ); // Z
alert( String.fromCodePoint(0x5a) ); // Z (          )

<<<<<<< HEAD Unicode \u hex :

```js run
// 5a  90      16   
alert( '\u005a' ); // Z
```

65..220 ( ):

Now lets see the characters with codes 65..220 (the latin alphabet and a little bit extra) by making a string of them:

18b1314af4e0ead5a2b10bb4bacd24cecbb3f18e

let str = '';

for (let i = 65; i <= 220; i++) {
  str += String.fromCodePoint(i);
}
alert( str );
// Output:
// ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
// 

.

a > Z.

. . a (97) Z (90) .

  • .
  • . a z .

.

.

<<<<<<< HEAD (IE10 Intl.js ) ECMA-402 .

Luckily, modern browsers support the internationalization standard ECMA-402.

18b1314af4e0ead5a2b10bb4bacd24cecbb3f18e

.

str.localeCompare(str2) str str2 :

  • str str2 .
  • str str2 .
  • 0 .

:

alert( 'sterreich'.localeCompare('Zealand') ); // -1

( ) "a" "" .

<<<<<<< HEAD

Unicode

. .

Unicode

Unicode .

1-4 .

Unicode :

  • \xXX Unicode U+00XX .

    XX 00 FF \xXX 256 Unicode ( 128 ASCII ).

    256 . "\x7A" "z" (Unicode U+007A).

  • /uXXXX Unicode U+XXXX ( XXXX UTF-16 ).

    XXXX 4 0000 FFFF \uXXXX 65536 . Unicode U+FFFF surrogate pair (: ) ( ).

  • u{XXXXXXX} Unicode ( UTF-32 ).

    XXXXXXX 1 6 0 10FFFF ( Unicode). Unicode .

Unicode:

alert( "\uA9" ); //   

alert( "\u00A9" ); //         4 
alert( "\u044F" ); //  cyrillic  
alert( "\u2191" ); // ,     

alert( "\u{20331}" ); //  ( Unicode)     
alert( "\u{1F60D}" ); //  (  Unicode )    

2 . 2 .

UTF-16 2 . 2 65536 .

2 (surrogate pair) .

2 :

alert( ''.length ); // 2 X    
alert( ''.length ); // 2    
alert( ''.length ); // 2     

!

length 2 .

.

:

alert( ''[0] ); // ... 
alert( ''[1] ); //    ...

. alert .

: 0xd800..0xdbff . ( ) 0xdc00..0xdfff . .

String.fromCodePoint str.codePointAt .

String.fromCharCode str.charCodeAt .

:

//             charCodeAt

alert( ''.charCodeAt(0).toString(16) ); // d835

//     codePointAt
alert( ''.codePointAt(0).toString(16) ); // 1d4b3       

1 ( ) :

alert( ''.charCodeAt(1).toString(16) ); // dcb3
alert( ''.codePointAt(1).toString(16) ); // dcb3
//    

. .

:

We cant just split a string at an arbitrary position, e.g. take str.slice(0, 4) and expect it to be a valid string, e.g.: str.slic(0, 4) :

alert( 'hi '.slice(0, 4) ); //  hi [?]

( ).

. .

/ .

a .

UTF-16 . .

UTF-16 Unicode : .

S ( \u0307) .

alert( 'S\u0307' ); // 

( ) .

( \u0323) S : .

:

alert( 'S\u0307\u0323' ); // 

: Unicode .

:

let s1 = 'S\u0307\u0323'; //    +   + S
let s2 = 'S\u0323\u0307'; //    +   + S

alert( `s1: ${s1}, s2: ${s2}` );

alert( s1 == s2 ); // (!) false      

Unicode .

str.normalize() .

alert( "S\u0307\u0323".normalize() == "S\u0323\u0307".normalize() ); // true

normalize() 3 : \u1e68 (S ).

alert( "S\u0307\u0323".normalize().length ); // 1

alert( "S\u0307\u0323".normalize() == "\u1e68" ); // true

. Unicode .

Unicode : Unicode .

  • 3 . Backtick ${}.
  • UTF-16 .
  • \n Unicode \u... .
  • [] .
  • slice substring .
  • toLowerCase/toUpperCase .
  • indexOf includes/startsWith/endsWith .
  • localeCompare . =======

Summary

  • There are 3 types of quotes. Backticks allow a string to span multiple lines and embed expressions ${}.
  • We can use special characters, such as a line break \n.
  • To get a character, use: [] or at method.
  • To get a substring, use: slice or substring.
  • To lowercase/uppercase a string, use: toLowerCase/toUpperCase.
  • To look for a substring, use: indexOf, or includes/startsWith/endsWith for simple checks.
  • To compare strings according to the language, use: localeCompare, otherwise they are compared by character codes.

18b1314af4e0ead5a2b10bb4bacd24cecbb3f18e

:

  • str.trim() ().
  • str.repeat(n) n .
  • .

<<<<<<< HEAD / (regular expression) . (Regular Expression) .

Strings also have methods for doing search/replace with regular expressions. But thats big topic, so its explained in a separate tutorial section (Regular Expression).

Also, as of now its important to know that strings are based on Unicode encoding, and hence therere issues with comparisons. Theres more about Unicode in the chapter . <<<<<<< HEAD

18b1314af4e0ead5a2b10bb4bacd24cecbb3f18e ======= 8d9ecb724c7df59774d1e5ffb5e5167740b7d321

: 5

ucFirst(str) str :

ucFirst("john") == "John";

sandbox .

.

:

let newStr = str[0].toUpperCase() + str.slice(1);

. str str[0] undefined undefined toUpperCase() .

:

function ucFirst(str) {
  if (!str) return str;

  return str[0].toUpperCase() + str.slice(1);
}

alert( ucFirst("john") ); // John

sandbox.

: 5

checkSpam(str) str viagra XXX true false.

:

checkSpam('buy ViAgRA now') == true
checkSpam('free xxxxx') == true
checkSpam("innocent rabbit") == false

sandbox .

:

function checkSpam(str) {
  let lowerStr = str.toLowerCase();

  return lowerStr.includes('viagra') || lowerStr.includes('xxx');
}

alert( checkSpam('buy ViAgRA now') );
alert( checkSpam('free xxxxx') );
alert( checkSpam("innocent rabbit") );

sandbox.

: 5

truncate(str, maxlength) str maxlength str "" maxlength .

( ).

:

truncate("What I'd like to tell on this topic is:", 20) = "What I'd like to te"

truncate("Hi everyone!", 20) = "Hi everyone!"

sandbox .

maxlength .

Unicode . .

function truncate(str, maxlength) {
  return (str.length > maxlength) ?
    str.slice(0, maxlength - 1) + '' : str;
}
function truncate(str, maxlength) {
  return (str.length > maxlength) ?
    str.slice(0, maxlength - 1) + '' : str;
}

sandbox.

: 4

"$120" . .

extractCurrencyValue(str) .

:

alert( extractCurrencyValue('$120') === 120 ); // true

sandbox .

function extractCurrencyValue(str) {
  return +str.slice(1);
}
function extractCurrencyValue(str) {
  return +str.slice(1);
}

sandbox.


Web Proxy Viewer  |  New URL  |  Original Page