不確定我是否正確表達了這個問題,所以這里是一個例子
let string = "Test text ab/c test
Test t/est
### Test/
Test t/test
Test test"
我希望/只從其中包含的行中洗掉,###所以它最終是這樣的:
Test text ab/c test
Test t/est
### Test
Test t/test
Test test
我假設我可以使用
mystring.replace(/\/g, '')
但是我如何指定它只需要\在行中洗掉###
uj5u.com熱心網友回復:
您可以拆分換行符,然后再次加入它們。
let string = `Test text ab/c test
Test t/est
### Test/
Test t/test
Test test
Test// ### test /
`
const parts = string.split("\n")
.map(s => s.includes("###") ? s.replace(/\//g, '') : s)
.join("\n");
console.log(parts);
uj5u.com熱心網友回復:
您可以使用
string.replace(/(?<=###.*)\/|\/(?=.*###)/g, '')
該(?<=###.*)\/|\/(?=.*###)正則運算式匹配/是任一前面有炭###和任何零個或多個非線斷線字符,或之后具有零個或多個非線斷線字符,然后###。
請參閱此 JavaScript 演示:
let string = "Test text ab/c test\nTest t/est\n### /T/e/s/t/\nTest t/test\nTest test"
console.log(string.replace(/(?<=###.*)\/|\/(?=.*###)/g, ''))
另一種解決方案:將攪拌分成幾行,然后map將結果陣列和子字串/中的專案中includes的所有字符都洗掉###,然后將字串連接回來:
let string = "Test text ab/c test\nTest t/est\n### /T/e/s/t/\nTest t/test\nTest test"
console.log( string.split("\n").map(line => line.indexOf('###') > -1 ? line.replace(/\//g, '') : line).join("\n") )
uj5u.com熱心網友回復:
.replace()整個段然后回傳所有內容,但 \/(\前綴為 to/以逃避它。
const str = `
Test text ab/c test
Test t/est
### Test/
Test t/test
Test test`;
const rgx = /(###. )\//gm;
const sub = `$1`;
console.log(str.replace(rgx, sub));
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/376390.html
標籤:javascript html 正则表达式 细绳
下一篇:如何計算所有產品的折扣
