To slightly modify a string, like replacing its first character to capital or last character from comma to period, there are two ways to achieve.
use replace()
with regex
There are two things worth notice:
- without using regular expression, only the first-matched substring will be replaced.
-
replace()
function returns a new string and left the old string unchanged.
// replace the last comma to period
let names = "anne, ben, carol, dennis, evans,";
names = names.replace(/,$/, '.');
// anne, ben, carol, dennis, evans.
use slice()
and append
// replace the last comma to period
let names = "anne, ben, carol, dennis, evans,";
names = names.slice(0, -1) + '.';
// anne, ben, carol, dennis, evans.
slice(indexStart, indexEnd)
and substring(indexStart, indexEnd)
are almost identical with some slight differences:
-
indexEnd
is optional in both functions, if not specified it would extract to the end of the string. Otherwise, it is the first character to exclude. - If value is less than 0 or
NaN
,substring()
would consider 0.slice()
would considerNaN
0, and negative values count backwards from the end. - If value is greater than
stringName.length
, it would considerstringName.length
in both functions. -
substring()
swap the arguements ifindexStart
is greater thanindexEnd
,slice()
returns an empty string.
Top comments (0)