我想删除字符串周围的“”。

例如,如果字符串是:“I am here”,那么我只想输出I am here。


当前回答

如果你只想删除边界引号:

function stripquotes(a) {
    if (a.charAt(0) === '"' && a.charAt(a.length-1) === '"') {
        return a.substr(1, a.length-2);
    }
    return a;
}

如果字符串看起来不像“带引号的文本”,这种方法不会触及字符串。

其他回答

如果字符串保证在开头和结尾有一个引号(或任何其他单个字符),你想删除:

str = str.slice(1, -1);

Slice的开销比正则表达式小得多。

这是为懒人设计的一款简单的工具

var str = '"a string"';
str = str.replace(/^"|"$/g, '');
str = str.replace(/^"(.*)"$/, '$1');

只有当引号是字符串的第一个和最后一个字符时,这个regexp才会删除引号。F.ex:

"I am here"  => I am here (replaced)
I "am" here  => I "am" here (untouched)
I am here"   => I am here" (untouched)

这工作…

var string1 = "'foo'"; var string2 = '"bar"'; function removeFirstAndLastQuotes(str){ var firstChar = str.charAt(0); var lastChar = str[str.length -1]; //double quotes if(firstChar && lastChar === String.fromCharCode(34)){ str = str.slice(1, -1); } //single quotes if(firstChar && lastChar === String.fromCharCode(39)){ str = str.slice(1, -1); } return str; } console.log(removeFirstAndLastQuotes(string1)); console.log(removeFirstAndLastQuotes(string2));

如果你只想删除边界引号:

function stripquotes(a) {
    if (a.charAt(0) === '"' && a.charAt(a.length-1) === '"') {
        return a.substr(1, a.length-2);
    }
    return a;
}

如果字符串看起来不像“带引号的文本”,这种方法不会触及字符串。