search

Home  >  Q&A  >  body text

How can I convert spaces to "-" in a string and then convert it back to the original string?

Hello, I have a string variable

var str = "Air Quality - Indoor"

I convert it to

var str2 = str.replace(/-/g, '').replace(/\s+/g, '-').toLowerCase()
//air-quality-indoor

So how to convert "air-quality-indoor" into "Air Quality - Indoor" again?

P粉936509635P粉936509635502 days ago655

reply all(1)I'll reply

  • P粉447002127

    P粉4470021272023-09-12 11:42:37

    Titlecase function obtained from titlecase, below is a sample code.

    let str = "Air Quality - Indoor";
    str = transform(str);
    console.log(str);
    str = transform(str);
    console.log(str);
    
    function transform(str) {
      if (str.includes(' ')) {
        return str.replace(/-/g, '').replace(/\s+/g, '-').toLowerCase()
      } else {
        return titleCase(str.replace(/-/g, ' ')).replace(/\b(\w+)$/g, '- ');
      }
    }
    
    function titleCase(str) {
      return str.toLowerCase().split(' ').map(function(word) {
        return (word.charAt(0).toUpperCase() + word.slice(1));
      }).join(' ');
    }

    reply
    0
  • Cancelreply