The replace()
method can be used in a TypeScript string to replace a particular substring or a match (regular expression) in a string. All we need to do is pass the substring or regular expression of the substring we want to replace.
string.replace(substring|regex, replacement)
substring
: This is the substring of a string string
that we want to replace.regex
: This is used as a regular expression to match the substring we want to replace.replacement
: This is what we want to use as a replacement to the regex
or substring
.The value returned is a new string.
export {} // create some strings let name:string = "Onyejiaku Doe" let role:string = "Musician" let language:string = "JavaScript Language" // create some replacements let rep1 = "Theodore" let rep2 = "Author" let rep3 = "TypeScript" // replace some substrings console.log(name.replace("Doe", rep1)) console.log(role.replace(/Musician/gi, rep2)) console.log(language.replace("JavaScript", rep3))
replace()
method, we replace some substrings and print the new strings to the console. RELATED TAGS
CONTRIBUTOR
View all Courses