跳过或删除字符串中 pre 和 code 标签内的换行符
Skip or remove newline within pre and code tags in string
所以目前我正在努力尝试显示格式化代码的效果,或者在本例中是我的 React 应用程序中的 graphql 操作。由状态触发,我想显示或删除某些变量。
const testing = `query {
getBooks {
${value.bookId?"id" : ""}
${value.bookEntry?"entry" : ""}
${value.bookTitle?"title" : ""}
}
}`
...
<div className="output">
<pre>
<code>{testing}</code>
</pre>
</div>
我无法渲染看起来像 this!
的东西
可能有更好的方法来解决这个问题,但值得一问!
添加过滤器以在渲染前删除空格。
检查下面我的解决方案:
// Solution:
function clearQueryString(queryString){
const result = []
const splitted = queryString.split('\n')
console.log({splitted})
for (let index = 0; index < splitted.length; index++) {
const element = splitted[index];
// regex credit:
if (!element.replace(/\s/g, '').length) {
console.log(`#${index} string only contains whitespace!`);
} else {
result.push(element)
}
}
return result.join('\n')
}
// Usage:
const value = {}
const testing = `query {
getBooks {
${value.bookId?"id" : ""}
${value.bookEntry?"entry" : ""}
${value.bookTitle?"title" : ""}
author
otherfield
}
}`
document.getElementById('codeOutput').innerHTML = clearQueryString(testing);
<div className="output">
<pre>
<code id="codeOutput"></code>
</pre>
</div>
所以目前我正在努力尝试显示格式化代码的效果,或者在本例中是我的 React 应用程序中的 graphql 操作。由状态触发,我想显示或删除某些变量。
const testing = `query {
getBooks {
${value.bookId?"id" : ""}
${value.bookEntry?"entry" : ""}
${value.bookTitle?"title" : ""}
}
}`
...
<div className="output">
<pre>
<code>{testing}</code>
</pre>
</div>
我无法渲染看起来像 this!
的东西可能有更好的方法来解决这个问题,但值得一问!
添加过滤器以在渲染前删除空格。
检查下面我的解决方案:
// Solution:
function clearQueryString(queryString){
const result = []
const splitted = queryString.split('\n')
console.log({splitted})
for (let index = 0; index < splitted.length; index++) {
const element = splitted[index];
// regex credit:
if (!element.replace(/\s/g, '').length) {
console.log(`#${index} string only contains whitespace!`);
} else {
result.push(element)
}
}
return result.join('\n')
}
// Usage:
const value = {}
const testing = `query {
getBooks {
${value.bookId?"id" : ""}
${value.bookEntry?"entry" : ""}
${value.bookTitle?"title" : ""}
author
otherfield
}
}`
document.getElementById('codeOutput').innerHTML = clearQueryString(testing);
<div className="output">
<pre>
<code id="codeOutput"></code>
</pre>
</div>