我想改变
每个单引号转双引号 和 每个双引号转为单引号
在 jquery 或 js 中。
var myString = " tes't tes\"t tes\"t te'st ";
console.log(myString);
for (i = 0; i < myString.length; i++) {
console.log(myString[i]);
if (myString[i] == "'") {
myString[i] == "\"";
continue;
}
if (myString[i] == "\"") {
myString[i] == "'";
continue;
}
}
console.log(myString);
但是我的功能运行得不好。 请纠正我。
最佳答案
在 if
中,您没有进行赋值 (myString[i] == "\"";
),而是进行比较。这可能应该是single =
。唯一的问题是,字符串是不可变的,因此这不会按预期工作。解决方案,构建一个新字符串:
function flipQuotes(str) {
var result = [], i = 0, lim = str.length, c;
for (; i < lim; i += 1) {
c = str.charAt(i);
switch(c) {
case '"':
result.push("'");
break;
case "'":
result.push('"');
break;
default:
result.push(c);
}
}
return result.join('');
}
var myString = " tes't tes\"t tes\"t te'st ";
console.log(
flipQuotes(myString) // => ' tes"t tes't tes't te"st '
);
关于javascript - javascript中单引号转双引号,以及双引号转单引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14334832/