用逗号替换字符串中的空格

时间:2018-07-06 20:03:11

标签: javascript string replace

我正在尝试用逗号替换字符串中的空格。字符串看起来像这样

'1529954897.543 GET 200 173481 174274 "https://www.facebook.com/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/67.0.3391.0 Safari/537.36" "-" 1 0'

现在的问题是,当我替换所有空格时,它还会替换子字符串“ Mozilla / 5.0(X11; Linux x86_64)AppleWebKit / 537.36(KHTML,如Gecko)HeadlessChrome / 67.0.3391.0 Safari / 537.36“。

有没有办法不能替换字符串中字符串的空格?

我期望的输出是

'1529954897.543,GET,200,173481,174274,"https://www.facebook.com/","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/67.0.3391.0 Safari/537.36","-",1,0'

2 个答案:

答案 0 :(得分:4)

您可以使用某些split / join逻辑仅替换“ ..”之外的空格:

const input = '1529954897.543 GET 200 173481 174274 "https://www.facebook.com/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/67.0.3391.0 Safari/537.36" "-" 1 0'

let result = input.split(`"`)
  .map((part, i) => i % 2 ?
    part :
    part.split(" ").join(",")
  ).join(`"`)

console.log(result)

答案 1 :(得分:1)

您可以逐个字符地对其进行解析。这是一个简单的实现:

function parsestr(str) {
  var tokens = [], i, ch, token = "", in_quote = false;
  for (i = 0; i < str.length; i++) {
    var ch = str.charAt(i);
    if (ch === '"') {
      in_quote = !in_quote;
    } else if (ch === ' ' && in_quote === false) {
      tokens.push(token);
      token = "";
    } else {
      token += ch;
    }
  }
  if (token) {
    tokens.push(token);
  }
  return tokens;
}
var str = '1529954897.543 GET 200 173481 174274 "https://www.facebook.com/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/67.0.3391.0 Safari/537.36" "-" 1 0'
console.log(parsestr(str));