gpt4 book ai didi

javascript - 使字符串小写尊重引号 - Javascript

转载 作者:行者123 更新时间:2023-11-30 16:47:03 24 4
gpt4 key购买 nike

我正在为 Domain Specific Language, 构建解析器(或 DSL,)我正在尝试将字符串转换为全部小写。我知道 toLowerCase 可以轻松完成此任务,但我需要保留用双引号或单引号("')引起来的字符串在其原始情况下。例如,请参见以下内容:

输入:这是一个“串起你们”的测试,因为你们可以看到“你好,我的”

输出:这是一个测试“sTriNg Y'alL”,正如您所看到的“hEllO woRl\'o miNE'”

编辑:添加反斜杠引号

最佳答案

只是拼凑了一个快速解析器,不确定它的效果如何,但它应该处理无限制的反斜杠转义

function string_to_block(str) {
var blocks = [],
i, j, k;
function isEscaped(str, i) {
var escaped = false;
while (str[--i] === '\\') escaped = !escaped;
return escaped;
}
start: for (i = 0; i < str.length; i = j + 1) {
find: for (j = i; j < str.length; ++j) {
if (str[j] === '"' && !isEscaped(str, j)) {
if (j > i) {
blocks.push({type: 'regular', str: str.slice(i, j)});
}
end: for (k = j + 1; k < str.length; ++k) {
if (str[k] === '"' && !isEscaped(str, k)) {
// found a "str" block
blocks.push({type: 'quote', str: str.slice(j, k + 1)});
j = k;
break find;
}
}
throw new SyntaxError('unclosed "str... starting at index ' + j);
}
if (str[j] === "'" && !isEscaped(str, j)) {
if (j > i) {
blocks.push({type: 'regular', str: str.slice(i, j)});
}
end: for (k = j + 1; k < str.length; ++k) {
if (str[k] === "'" && !isEscaped(str, k)) {
// found a 'str' block
blocks.push({type: 'quote', str: str.slice(j, k + 1)});
j = k;
break find;
}
}
throw new SyntaxError("unclosed 'str... starting at index " + j);
}
}
}
if (k + 1 < str.length) {
blocks.push({type: 'regular', str: str.slice(k + 1)});
}
return blocks;
}

现在

var foo = string_to_block("ThIs iS a teST \"sTriNg Y'alL\" aS yOu cAN sEE 'hEllO woRl\\' o miNE'");
/*
[
{"type": "regular", "str": "ThIs iS a teST "},
{"type": "quote" , "str": "\"sTriNg Y'alL\""},
{"type": "regular", "str": " aS yOu cAN sEE "},
{"type": "quote" , "str": "'hEllO woRl\\' o miNE'"}
]
*/

因此我们可以根据需要重新构建您的字符串;

var i, str = '';
for (i = 0; i < foo.length; ++i) {
if (foo[i].type === 'regular') str += foo[i].str.toLowerCase();
else str += foo[i].str;
}
str; // this is a test "sTriNg Y'alL" as you can see 'hEllO woRl\' o miNE'

关于javascript - 使字符串小写尊重引号 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31077634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com