gpt4 book ai didi

javascript - 通过正则表达式将单引号更改为双引号。 (单字)

转载 作者:行者123 更新时间:2023-11-30 08:24:50 29 4
gpt4 key购买 nike

我尝试通过正则表达式将文本中的单引号更改为双引号。 (单字)示例:我走了。 You gona fly to planet 'Ziqtos' => 我需要在 I'm 中保留单引号,并在 You gona fly "Ziqtos"< 中改为双引号/strong> 请帮忙。这是我的代码。

    var myStr = "I, I can't deny I'm paralysed from the 'inside' Everyday I wake to feel the same And 'every' time you 'ask' me how I'm feeling I just smile and tell you 'that' I'm fine I, I don't know why I'm terrified of everything Just to call the doctor seems daunting For most of my life I felt a sharp uncertainty Now its just become a part of me I, I can't deny I'm paralysed from the inside Everyday I wake to feel the 'same' And every time you ask me how I'm feeling I just smile and tell you that I'm fine It's hard to stay true, to myself and to you I can't measure up to this girl you thought you knew This aching in my heart is tearing me apart But, darling all your love is somehow not 'enough' This aching in my heart is tearing me apart But, darling all your love is somehow not"

var newStr = "";

for (var i = 0; i < myStr.length; i++) {
var lastIndex = myStr.search(/\s'[a-zA-Z]/ || /[a-zA-Z]'\s/);
newStr += myStr.substr(0, lastIndex + 1);
newStr += '\"';
myStr = myStr.substr(lastIndex + 2);
}

var Phar = document.createElement("p");
Phar.innerHTML = newStr;
document.body.appendChild(Phar);

最佳答案

代码

See regex in use here

\B'|'\B

或者,您可以使用 \B'(\w+)'\B 并替换为 "$1"

用法

const regex = /\B'|'\B/g;
const str = `I'm go. You gona fly to planet 'Ziqtos'`;
const str2 = `I, I can't deny I'm paralysed from the 'inside' Everyday I wake to feel the same And 'every' time you 'ask' me how I'm feeling I just smile and tell you 'that' I'm fine I, I don't know why I'm terrified of everything Just to call the doctor seems daunting For most of my life I felt a sharp uncertainty Now its just become a part of me I, I can't deny I'm paralysed from the inside Everyday I wake to feel the 'same' And every time you ask me how I'm feeling I just smile and tell you that I'm fine It's hard to stay true, to myself and to you I can't measure up to this girl you thought you knew This aching in my heart is tearing me apart But, darling all your love is somehow not 'enough' This aching in my heart is tearing me apart But, darling all your love is somehow not`;
const subst = `"`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
const result2 = str2.replace(regex, subst);

console.log(result);
console.log(result2);


结果

输入

I'm go. You gona fly to planet 'Ziqtos'

输出

I'm go. You gona fly to planet "Ziqtos"

解释

  • \B 断言 \b 不匹配的位置
  • ' 按字面匹配撇号字符

关于javascript - 通过正则表达式将单引号更改为双引号。 (单字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47463356/

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