創建一個接受字串作為輸入的函式,洗掉括號之間的所有內容,并回傳修改后的字串。如果左右括號數量不匹配,則回傳空字串
我必須創建一個函式來洗掉括號之間的所有內容并回傳沒有它的字串。
例如,此輸入12(3(45))67(8)9將回傳此輸出12679。
如果括號的數量不正確,則回傳一個空字串。
這是我的方法:
function removeContent(str) {
let leftP = 0, rightP = 0;
// wrong number of parentheses scenario
for( let i = 0; i < str.length; i ) {
if(str[i] === '(' ) leftP ;
if(str[i] === ')' ) rightP ;
}
if( leftP !== rightP) return "";
// remove the content otherwise
}
console.log(removeContent('12(3(45))67(8)9'));
不知道如何做配對括號之間的組合和洗掉內容。
uj5u.com熱心網友回復:
一個簡單的方法是跟蹤括號計數,然后僅在括號計數等于 0 時輸出字母。
最后,如果括號計數不為零,您還可以告訴它根據要求回傳空字串。
例如..
function removeContent(string) {
let bracketCount = 0;
let output = '';
for (const letter of string) {
if (letter === '(') bracketCount = 1
else if (letter === ')') bracketCount -= 1
else if (bracketCount === 0) output = letter;
}
return bracketCount === 0 ? output : '';
}
console.log(removeContent('12(3(45))67(8)9'));
console.log(removeContent('12(345))67(8)9'));
console.log(removeContent('1(2)(3)45(7)8(((9)))77'));
uj5u.com熱心網友回復:
用正則運算式做一個查找替換 /\( [\d\(]*\) /g
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/337492.html
下一篇:如何在不同的單詞中拆分字串
