从字符串Javascript中删除不需要的引号



我有一个字符串,输出如下:

"firstName" "lastName"

我需要像一样输出

"firtName lastName"

否则我会收到错误的字符串请求。我尝试了不同的regex组合,可以实现这一点,但到目前为止,我可以删除字符串开头和结尾的引号以及在中间的引号。

var string = '"firstName" ,"lastName"';
var stringWithoutCommas = string.replace(/,/g, '');
var stringWithoutExtQuotes = stringWithoutCommas.replace(/^"(.+(?="$))"$/, '$1');
console.log(stringWithoutExtQuotes); //firstName" "lastName

谢谢。

var string = '"firstName" ,"lastName"';
console.log(
string.replace(/"(w*)W*(w*)"/, function(_, match1, match2){
return `"${match1} ${match2}"`;
})
);

您可以获取这两个字符串,然后重新构建所需的字符串。

一种方法

const input = '"firstName" "lastName"'
console.log('"'+input.replace(/"(.+?)"/g,'$1')+'"')

提取双引号之间的所有内容并连接结果:

const string = '"firstName" ,"lastName"';
console.log(Array.from(string.matchAll(/"([^"]+)"/g), x=>x[1]).join(" "));

Regex"([^"]+)"

解释

--------------------------------------------------------------------------------
"                        '"'
--------------------------------------------------------------------------------
(                        group and capture to 1:
--------------------------------------------------------------------------------
[^"]+                    any character except: '"' (1 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
)                        end of 1
--------------------------------------------------------------------------------
"                        '"'

见证明。

这应该是您问题的答案。

function myFunction() {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var result = fruits.join(",");
}

最新更新