I am attempting to write a function that takes an array of characters that make up a string (including the start and end '"') and returns the string that makes up the array.
我正在尝试编写一个函数,它接受构成字符串的字符数组(包括开头和结尾'“')并返回组成数组的字符串。
example input / output:
示例输入/输出:
input = ['"', 'h', 'e', 'l', 'l', 'o', ' ', 't', 'h', 'e', 'r', 'e', '"'];
output = "hello there";
or:
EDIT (clarify invalid array example):
编辑(澄清无效的数组示例):
var str = '"\\\\\\"\\"x\\""'
JSON.parse(str); // returns "\\"\"x\""
// I want my function to work the same way but after converting the str to an array
var array = str.split("");
Right now I have the following:
现在我有以下内容:
var makeString = function(array){
var result = "";
var arr = string.split('');
var runner = true;
var i = 1;
while (arr[i]){
// This if statement doesn't work, but it is intended to
// account for any double quotes inside the string
if (arr[i] === '"' && arr[i-1] !== '\\'){
return result;
}
result += arr[i];
i++;
}
};
my function doesn't really work, but I also need it to account for all uses of escape characters and \r \n \t etc (which I don't really understand in the first place).
我的功能并没有真正起作用,但我还需要它来解释转义字符和\ r \ n \ t等的所有用法(我一开始并不是真的理解)。
EDIT / addition: from https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js I am trying to create something like crockford did to parse a string with the sub function, except I want to take the current state of the input and convert it to an array and parse it through the array elements.
编辑/补充:来自https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js我试图创建类似crockford的东西,用子函数解析一个字符串,除了我想要输入的当前状态并将其转换为数组并通过数组元素进行解析。
string = function () {
// Parse a string value.
var hex,
i,
string = '',
uffff;
// When parsing for string values, we must look for " and \ characters.
if (ch === '"') {
while (next()) {
if (ch === '"') {
next();
return string;
}
if (ch === '\\') {
next();
if (ch === 'u') {
uffff = 0;
for (i = 0; i < 4; i += 1) {
hex = parseInt(next(), 16);
if (!isFinite(hex)) {
break;
}
uffff = uffff * 16 + hex;
}
string += String.fromCharCode(uffff);
} else if (typeof escapee[ch] === 'string') {
string += escapee[ch];
} else {
break;
}
} else {
string += ch;
}
}
}
error("Bad string");
},
1 个解决方案
#1
0
To strip out the escape characters, you need to use the string's replace
function and take in a regex as a parameter
要删除转义字符,您需要使用字符串的替换函数并将正则表达式作为参数
function arrayToString(array) {
return array.join('').replace(/[\\\"]/g, "")
}
Test Case
var input = ['"', 'h', 'e', 'l', 'l', 'o', ' ', 't', 'h', 'e', 'r', 'e', '"'];
arrayToString(input)
=> "hello there"
#1
0
To strip out the escape characters, you need to use the string's replace
function and take in a regex as a parameter
要删除转义字符,您需要使用字符串的替换函数并将正则表达式作为参数
function arrayToString(array) {
return array.join('').replace(/[\\\"]/g, "")
}
Test Case
var input = ['"', 'h', 'e', 'l', 'l', 'o', ' ', 't', 'h', 'e', 'r', 'e', '"'];
arrayToString(input)
=> "hello there"