简体   繁体   中英

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". 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)?

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.

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.

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:

 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. Then use a replace function to return an empty string or the quoted string, as appropriate:

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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