Convert a string to a new string in javascript
A simple one!
In JavaScript, you can convert a string to a new string using various methods. Here are a few examples:
- Concatenation: You can concatenate two strings using the
+
operator.const originalString = "Hello"; const newString = originalString + " World"; console.log(newString); // Output: "Hello World"
- Template Literals: You can use template literals to create a new string by concatenating strings and variables.
const originalString = "Hello"; const name = "John"; const newString = `${originalString} ${name}`; console.log(newString); // Output: "Hello John"
- String.prototype.concat(): You can use the
concat()
method to concatenate two strings.const originalString = "Hello"; const newString = originalString.concat(" World"); console.log(newString); // Output: "Hello World"
- String.prototype.replace(): You can use the
replace()
method to replace a part of the original string with a new string.const originalString = "Hello World"; const newString = originalString.replace("World", "Earth"); console.log(newString); // Output: "Hello Earth"
- String.prototype.substring(): You can use the
substring()
method to extract a part of the original string and create a new string.const originalString = "Hello World"; const newString = originalString.substring(6); // Extract from index 6 to the end console.log(newString); // Output: " World"
These are just a few examples of how you can convert a string to a new string in JavaScript. The choice of method depends on the specific use case and the desired outcome.