Javascript string
- User
Javascript string
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Javascript string
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
JavaScript strings are sequences of characters used to represent text, created using single quotes (' '), double quotes (" "), or backticks (` `). They are immutable, meaning any operation produces a new string rather than modifying the original[1][2][8]. Below are key aspects of JavaScript strings:
const str1 = "Hello";
const str2 = `Template literal`;
new String() (not recommended due to unexpected behavior in comparisons and performance)[1][7]:
const strObj = new String("Hello"); // typeof strObj → "object"
Length: str.length returns the number of characters[2][3][4].
Character Access:
str.charAt(index) or str[index] (returns undefined for invalid indices)[1][4][6].str.charCodeAt(index) returns the UTF-16 code[2].Substring Extraction:
| Method | Description | Handles Negative Indices |
|---|---|---|
slice(start, end) | Extracts from start to end (exclusive) | Yes |
substring(start, end) | Similar to slice but treats negative indices as 0 | No |
substr(start, length) | Extracts length characters starting from start (deprecated) | Yes (start only) |
| Example: |
"mozilla".slice(1, 4); // "ozi"
"mozilla".substring(1, 4); // "ozi"
"mozilla".substr(1, 3); // "ozi"
Searching:
indexOf(substr) returns the first occurrence’s index or -1[4][6].includes(substr) checks for substring presence[6].const name = "Alice";
const greeting = `Hello, ${name}!`; // "Hello, Alice!"
const multiLine = `Line 1
Line 2`;
+ or template literals[5][8]:
const result = "Hello, " + "World!"; // "Hello, World!"
toUpperCase() return new strings[2][6]:
const original = "abc";
const upper = original.toUpperCase(); // "ABC" (original remains "abc")
String objects[1][7].substr() in favor of slice() or substring()[6].By leveraging these features, you can efficiently handle text manipulation in JavaScript while avoiding common pitfalls.