Masatoshi Nishiguchi
Masatoshi Nishiguchi's Blog

Masatoshi Nishiguchi's Blog

Parameterize string in JavaStript

Masatoshi Nishiguchi's photo
Masatoshi Nishiguchi
·Mar 17, 2018·

1 min read

It is nice to know how to convert any text into hyphenated string.

const parameterize = (string) =>
  string
    .toLowerCase()
    .replace(/[^a-zA-Z0-9 -]/g, ' ') // convert unwanted chars to spaces
    .replace(/\s\s+/g, ' ')          // convert multi spaces to single space
    .replace(/\s/g, '-')             // convert spaces to hyphens
    .replace(/--+/g, '-');           // convert multi hyphens to single hyphen
parameterize('Masatoshi.Nishiguchi:;Software Engineer');
parameterize('Masatoshi/Nishiguchi~^Software Engineer');
parameterize('Masatoshi|Nishiguchi-=Software Engineer');
parameterize('Masatoshi%Nishiguchi_+Software Engineer');
//=> "masatoshi-nishiguchi-software-engineer"
 
Share this