Open In App

JavaScript Program to Add Prefix and Suffix to a String

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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
    )
);

Output
Geeks for Geeks

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
    )
);

Output
Geeks for Geeks

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
    )
);

Output
Geeks for Geeks


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads