JavaScript Program to Add Prefix and Suffix to a String
Last Updated :
17 Apr, 2024
In this article, we are going to implement a JavaScript program through which we can add a prefix and suffix to a given string. A prefix is added to the beginning of a word to modify its meaning. A suffix is added to the end of a word. Together, they form a prefix-suffix string, enabling the creation of new words or altering the existing word’s meaning or grammatical category.
Approach 1: Using String Concatenation
In this approach, we are using string concatenation to combine multiple strings. We took three strings as input: prefix, string, and suffix, and then we returned the concatenated form of these strings.
Syntax:
const stringFormation = (a, b, c) => {
return a + b + c;
};
Example: This example shows the use of the above-explained approach.
Javascript
const stringFormation = (
inputPrefix,
inputString,
inputSuffix
) => {
return (
inputPrefix +
inputString +
inputSuffix
);
};
let testCase1 = "Geeks";
let testCase2 = " for ";
let testCase3 = "Geeks";
console.log(
stringFormation(
testCase1,
testCase2,
testCase3
)
);
Approach 2: Using Array Spread Operator
In this approach we are using Array Spread Operator. We took three strings as input: prefix, string, and suffix, and then we are forming a string by joining them through join() method.
Syntax
const stringFormation = (a, b, c) => {
return [a, b, c].join("");
};
Example: This example shows the use of the above-explained approach.
Javascript
const stringFormation = (
inputPrefix,
inputString,
inputSuffix
) => {
return [
inputPrefix,
inputString,
inputSuffix,
].join("");
};
let testCase1 = "Geeks";
let testCase2 = " for ";
let testCase3 = "Geeks";
console.log(
stringFormation(
testCase1,
testCase2,
testCase3
)
);
Approach 4: Using Array Join
In this Approach we use the Array.join() method to concatenate the prefix, string, and suffix into a single string. By passing an array containing these elements to join(”), they are joined together without any separator, forming the desired result.
Example: In this example we defines a function stringFormation that concatenates three input strings. It then tests the function with three test cases and prints the result.
JavaScript
const stringFormation = (
inputPrefix,
inputString,
inputSuffix
) => {
return [inputPrefix, inputString, inputSuffix].join('');
};
let testCase1 = "Geeks";
let testCase2 = " for ";
let testCase3 = "Geeks";
console.log(
stringFormation(
testCase1,
testCase2,
testCase3
)
);
Share your thoughts in the comments
Please Login to comment...