Version: v0.8.1 - Beta.  We welcome contributors & feedback.

String.setChar

setChar($index, $newChar) -> self

Description

Replace a single character at $index.

If $index is negative, it counts from the end of the string.

The index must be inside the bounds of the string.

'abcdef'.setChar(1, 'X')
//= 'Xbcdef'

'abcdef'.setChar(3, 'X')
//= 'abXdef'

'abcdef'.setChar(-1, 'X')
//= 'abcdeX'

'abcdef'.setChar(100, 'X')
//= ERROR

Return Value

This function returns the new value without modifying the original variable.

$oldName = 'THE ROCKS'

$newName = $oldName.setChar(3, 'T')
//= 'THT ROCKS'

print($oldName)
//= 'THE ROCKS'

// Or you can use the self-assign shortcut.
$word = 'Free'
$word = .setChar(1, 'T')
//= 'Tree'

See Also