w3resource

JavaScript: Parameterize a string

JavaScript String: Exercise-7 with Solution

Parameterize String

Write a JavaScript function to parameterize a string.

Test Data:
console.log(string_parameterize("Robin Singh from USA."));
"robin-singh-from-usa"

Sample Solution:

JavaScript Code:

// Define a function named string_parameterize that takes a string str1 as input
string_parameterize = function (str1) {
    // Trim leading and trailing whitespace, convert to lowercase, and replace non-alphanumeric characters with an empty string
    return str1.trim().toLowerCase().replace(/[^a-zA-Z0-9 -]/, "").replace(/\s/g, "-");
};
// Output the result of calling the string_parameterize function with the input "Robin Singh from USA."
console.log(string_parameterize("Robin Singh from USA."));

Output:

robin-singh-from-usa

Explanation:

In the exercise above,

  • Define a function named "string_parameterize()" that takes a string 'str1' as input.
  • The function first trims leading and trailing whitespace from the input string.
  • It then converts the string to lowercase using the "toLowerCase()" method.
  • Next, it uses a regular expression (/[^a-zA-Z0-9 -]/) to remove any characters that are not alphanumeric, spaces, or hyphens from the string, replacing them with an empty string.
  • Finally, it replaces any remaining whitespace characters with hyphens using the "replace()" method.

Flowchart:

Flowchart: JavaScript  : Parameterize a string

Live Demo:

See the Pen JavaScript Parameterize a string - string-ex-7 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that converts a string to lowercase and replaces spaces with hyphens to create a URL slug.
  • Write a JavaScript function that removes special characters from a string before parameterizing it.
  • Write a JavaScript function that accepts a string and a replacement character for spaces, then outputs the parameterized string.
  • Write a JavaScript function that trims the string and then parameterizes it while handling multiple consecutive spaces.

Go to:


PREV : Hide Email Address.
NEXT : Capitalize First Letter.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.