Search code examples
javascriptstringvariableslocal-storagewhitespace

How to use a variable in Javascript as string and variable?


Is there a way to take a variable and use it as an input for the localStorage, then edit it to remove the spaces? What I have been trying to do is set a variable to the value of the local storage, then edit it. The problem is that Javascript won't allow me to use a string variable for this but I can't edit a normal variable. Here is my code:

    var retrieveLocal = localStorage.getItem('transferData');
retrieveLocal = retrieveLocal.replaceAll(\s+ , '');
  retrieveLocal = retrieveLocal.toLowerCase();
  console.log(retrieveLocal);

The error I'm getting is SyntaxError: Unexpected string (at index.html:11:5)


Solution

  • localStorage.setItem('transferData', "This is the simple string");
    var retrieveLocal = localStorage.getItem('transferData');
    console.log('retrieveLocal', retrieveLocal);
    const regex = / /g;
    retrieveLocal = retrieveLocal.replaceAll(regex, '');
    retrieveLocal = retrieveLocal.toLowerCase();
    console.log(retrieveLocal);

    localStorage.setItem('transferData', "This is the simple string");
    var retrieveLocal = localStorage.getItem('transferData');
    console.log('retrieveLocal', retrieveLocal);
    const regex = / /g;
    retrieveLocal = retrieveLocal.replaceAll(regex, '');
    retrieveLocal = retrieveLocal.toLowerCase();
    console.log(retrieveLocal);