英文:
javascript replace regex spaces and newlines
问题
I want
function main(){var a='hello';console.log(a);}
英文:
how to replace spaces and newlines together with additional closing code ;
in javascript?
function main(){
var a = 'hello'
console.log(a)
}
console.log(main.toString().replace(/[\n ]/g,''))
output
functionmain(){vara='hello'console.log(a)}
I want
function main(){var a='hello';console.log(a);}
答案1
得分: 1
以下是翻译好的内容:
也许这是正确的
function removeSpaces(str){
str = str.replace(/[\n]/g,';')
let res = str.replace(/[\n ;]/g,(e, i)=>{
switch(e){
case ';':
if(!'{:['.includes(str.substr(0, i).slice(-1))){
return ';'
}
default:
let arr = str.substr(0, i).split(' ')
let lastArr = arr[arr.length - 1]
// 需要空格的代码
if(['function','var','let','const'].includes(lastArr)){
return ' '
}
return ''
}
})
return res;
}
function main(){
var a = 'hello'
console.log(a)
}
let str = main.toString()
console.log(str.replace(/[\n ]/g,''))
let res = removeSpaces(str)
console.log(res) // function main(){var a='hello';console.log(a);}
英文:
maybe this is correct
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function removeSpaces(str){
str = str.replace(/[\n]/g,';')
let res = str.replace(/[\n ;]/g,(e, i)=>{
switch(e){
case ';':
if(!'{:['.includes(str.substr(0, i).slice(-1))){
return ';'
}
default:
let arr = str.substr(0, i).split(' ')
let lastArr = arr[arr.length - 1]
// need space code
if(['function','var','let','const'].includes(lastArr)){
return ' '
}
return ''
}
})
return res;
}
function main(){
var a = 'hello'
console.log(a)
}
let str = main.toString()
console.log(str.replace(/[\n ]/g,''))
let res = removeSpaces(str)
console.log(res) // function main(){var a='hello';console.log(a);}
<!-- end snippet -->
答案2
得分: 1
Based on your requirements, here is the translated content:
基于您的要求,我认为这个正则表达式可以完成任务:
1- 第一部分:
(?<![\{\}])[\n] -> 匹配没有分号的语句结束;
2- 第二部分:
([\{\}\;])(\n) -> 匹配{、}或;之后的换行符;
3- 第三部分:
\b\s\B|\B\s\b|\B\s\B -> 匹配空白字符
英文:
Based on your requirements, I think this regex can do the job:
/(?:(?<![\{\}])[\n]|([\{\}\;])(\n)|\b\s\B|\B\s\b|\B\s\B)/g
1- part one :
(?<![\{\}])[\n] -> matches ending of statements without ;
2- part two:
([\{\}\;])(\n) -> matches newlines after { or } or ;
3- part three:
\b\s\B|\B\s\b|\B\s\B ->match white spaces
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function main() {
var a = "hello"
console.log(a)
return 1;
}
const result = main.toString().replaceAll(
/(?:(?<![\{\}])[\n]|([\{\}\;])(\n)|\b\s\B|\B\s\b|\B\s\B)/g,
function (match, p1) {
if (match === "\n") return ";";
if (match === " ") return "";
return p1;
}
);
console.log(result);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论