从JavaScript中的字符串中删除子字符串
我有一个包含HTML和JSON字符串的字符串。。。我通过调用API检索这个字符串。 我的目标是从中检索JSON对象 我正在设置两个变量,其中包含html开头和结尾以及第三个空字符串从JavaScript中的字符串中删除子字符串,javascript,angular,Javascript,Angular,我有一个包含HTML和JSON字符串的字符串。。。我通过调用API检索这个字符串。 我的目标是从中检索JSON对象 我正在设置两个变量,其中包含html开头和结尾以及第三个空字符串 htmlStart = '<html><body><h1>Response</h1><p>The server returned these fields:<p><table border="1"><tr&g
htmlStart = '<html><body><h1>Response</h1><p>The server returned these fields:<p><table border="1"><tr><td>JSONResponse</td><td>';
htmlEnd = '</td></tr></table></body></html>';
response = '';
replace函数似乎不起作用。因为响应包含格式良好的HTML,所以您可以简单地将其视为一种格式
const responseElement=document.createElement('html');
responseElement.innerHTML=this.htmlStart;
const jsonString=responseElement.querySelector('td').textContent;
返回JSON.parse(jsonString);
由于响应包含格式良好的HTML,因此您可以简单地将其视为格式良好的HTML
const responseElement=document.createElement('html');
responseElement.innerHTML=this.htmlStart;
const jsonString=responseElement.querySelector('td').textContent;
返回JSON.parse(jsonString);
ngOnInit(): void {
this.apiService.getCategories().subscribe(
(res) => {
console.log(typeof res);
this.response = res
.replace(/\n/g, '')
.replace(this.htmlStart, '')
.replace(this.htmlEnd, '');
console.log(this.response);
}
);