简体   繁体   English

JavaScript如何从字符串中删除所有未引用的空格

[英]JavaScript how to remove all unquoted spaces from a string

Let's say you have the following string in JavaScript: unquoted string\\n "quoted string". 假设你在JavaScript中有以下字符串: unquoted string\\n "quoted string". How would you remove all the spaces (not including newlines) that are not inside the double quotes (possibly using the .replace method and some regex)? 如何删除不在双引号内的所有空格(不包括换行符)(可能使用.replace方法和一些正则表达式)?

EDIT: 编辑:

I'm making a game where the levels are being read from text files. 我正在制作一个从文本文件中读取关卡的游戏。 Therefore, in order to read from the level code more easily, I am trying to remove all the spaces except for the ones inside quotes. 因此,为了更容易地从级别代码中读取,我试图删除除引号内的所有空格。 I could try: levelString.replace(' ', '') , but that will remove all the spaces, including the ones inside quotes. 我可以尝试: levelString.replace(' ', '') ,但这将删除所有空格,包括引号内的空格。

One option is to check with look-ahead whether the number of remaining quotes is even -- which means the current space is not within quotes: 一种选择是预先检查剩余引号的数量是否为偶数 - 这意味着当前空间不在引号内:

[ ]+(?=[^"]*(?:"[^"]*"[^"]*)*$)

Replace with empty string. 替换为空字符串。 This assumes there is no escape mechanism for quotes. 这假设没有引号的转义机制。

Note that this is not very efficient. 请注意,这不是很有效。 A script that uses an old fashioned for loop and keeps track of being in/outside quotes will do a faster job. 使用旧式for循环并跟踪引号内/外引号的脚本可以更快地完成工作。

You could also use a simpler replace regular expression, and use a flag in the callback function for knowing whether you are in/outside quotes: 您还可以使用更简单的replace正则表达式,并在回调函数中使用标志来了解您是否在引号内/外:

 function removeSpaces(s) { let inside = 0; return s.replace(/ +|"/g, m => m === '"' ? (inside ^= 1, '"') : inside ? m : ''); } const result = removeSpaces('"this is inside" and this is outside. "back in again".'); console.log(result); 

The replace regex could match quoted strings and whitespace. replace正则表达式可以匹配引用的字符串和空格。 Then use a replace function to return an empty string or the quoted string, as appropriate: 然后使用replace函数根据需要返回空字符串或带引号的字符串:

 function removeSpaces(s) { return s.replace(/("[^"]*")|([ \\t]+)/g, (x) => { return x.charCodeAt(0) == 34 ? x : "" ; }) } const result = removeSpaces('"this is inside" and this is outside. "back in again".'); console.log(result); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM