英文:
How to use a variable in Javascript as string and variable?
问题
以下是翻译好的代码部分:
var retrieveLocal = localStorage.getItem('transferData');
retrieveLocal = retrieveLocal.replaceAll(/\s+/g, '');
retrieveLocal = retrieveLocal.toLowerCase();
console.log(retrieveLocal);
请注意,我修复了代码中的一个错误,将 replaceAll
中的正则表达式改为 /\\s+/g
以匹配所有空格字符。
英文:
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:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
var retrieveLocal = localStorage.getItem('transferData');
retrieveLocal = retrieveLocal.replaceAll(\s+ , '');
retrieveLocal = retrieveLocal.toLowerCase();
console.log(retrieveLocal);
<!-- end snippet -->
The error I'm getting is SyntaxError: Unexpected string (at index.html:11:5)
答案1
得分: 1
<!-- 开始代码段: JavaScript 隐藏: false 控制台: true Babel: false -->
<!-- 语言: lang-js -->
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);
<!-- 结束代码段 -->
<!-- 开始代码段: JavaScript 隐藏: false 控制台: true Babel: false -->
<!-- 语言: lang-js -->
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);
<!-- 结束代码段 -->
英文:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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);
<!-- end snippet -->
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论