[英]Javascript remove whitespaces in `strings`
我 JavaScript ` 在編寫大字符串時非常有用。 我的問題是它考慮了 JavaScript 之前的空白量。 因此,如果您的字符串在 JavaScript 中縮進,那么它也會在字符串中縮進。 有沒有辦法擺脫這個?
因為在這樣的示例中,我希望 html 標簽與字符串的左側齊平,但我不想使其與 JavaScript 的左側齊平。 檢查console.log 結果如何更好地理解它。
MyFunction = function() { console.log(` <html> <head> </head> <body> </body> </html> `); } MyFunction();
控制台日志:
由於您希望它們的html
標簽相對於左側齊平,但仍希望head
和body
相對地縮進,因此您要尋找的是用空字符串替換每行開頭的4個空格。
string.replace(/^ {4}/gm, '')
這是實時代碼..
MyFunction = function() { console.log(` <html> <head> </head> <body> </body> </html> `.replace(/^ {4}/gm, '')); } MyFunction();
我將執行以下操作:
MyFunction = function() {
/*however many spaces you want to remove from the front*/
const spaces = ' '; // four spaces
/* or */
const spacesRegex = /\s+/g;
let str = '';
const html = `
<html>
<head>
</head>
<body>
</body>
</html>
`.split('\n')
.forEach(line=>{
str += line.replace(spaces, '') + '\n';
});
console.log(str);
}
您可以用\\n
分割文本,在第一行啟示錄中找到縮進,然后從其余行中刪除它,然后再次加入。
MyFunction = function () { let indent = ""; console.log(` <html> <head> </head> <body> </body> </html> `.split("\\n").reduce((lines, line) => { if (!indent.length && line.trim()) { indent = line.match(/^(\\s+)/)[0]; } lines.push(line.replace(indent, "")); return lines; }, []).filter(line => line.length).join("\\n")); }; MyFunction();
您可以在新行之后match
空格,並獲得第一行的長度。 由此您可以構建一個可以替換它們的正則表達式:
let MyFunction = function(str) { let matches = str.match(/ +/g) let initial = matches[0].length // how big is the indent let re = RegExp(`\\n {${initial}}`, 'g') // remove these at the beginning of lines return str.replace(re, '\\n') } let str = ` <html> <head> </head> <body> <div> some text </div> </body> </html> ` console.log(MyFunction(str))
使用簡單的正則表達式來查找字符串的初始縮進可以使用/^[\\r\\n]?(\\s+)/
-結果可以用於再次對初始縮進進行換行。 這也利用了JS RegExp的性能。
如果您還希望刪除第一行和最后一行的換行符,只需在替換字符串后添加.trim()
。
function trimLeadingWS(str) { /* Get the initial indentation But ignore new line characters */ var matcher = /^[\\r\\n]?(\\s+)/; if(matcher.test(str)) { /* Replace the initial whitespace globally and over multiple lines */ return str.replace(new RegExp("^" + str.match(matcher)[1], "gm"), ""); } else { // Regex doesn't match so return the original string return str; } }; MyFunction = function() { console.log(trimLeadingWS('nothing to trim')); console.log(trimLeadingWS(` really quite some of (amount of spaces after line break should be ignored) indent to remove `)); console.log(trimLeadingWS(` <html> <head> </head> <body> </body> </html> `)); } MyFunction();
當然,有上千種方法可以到達您的目的地。 要僅使內容的縮進消失,您可以對模板字符串使用以下方法。 這確保只有模板字符串創建的縮進消失,但基本格式保持不變。
function trimIndent(strings, ...values) { const result = new Array(strings.length); result[0] = strings[0].replace(/^\n/, ''); const endIndex = strings.length - 1; result[endIndex] = strings[endIndex].replace(/\n$/, ''); var indent = result[0].match(/^\s+/g); result[0] = result[0].replace(/^\s+/, ''); for (let i = 0, m = result.length; i < m; i++) { var input = result[i]?? strings[i]; result[i] = input.replace(new RegExp('\n' + indent, "gm"), '\n'); } return result.flatMap((value, index) => { return value + (index < values.length? values[index]: '') }).join(""); } // example call: var user = { id: 10, name: "Kevin", } if (true) { console.log(trimIndent` <div> <span>ID: ${user.id}</span> <span> Username: ${user.name} </span> </div> `); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.