這個問題在這里已經有了答案: 回傳 Javascript 中正則運算式 match() 的位置? (12 個回答) 1 小時前關閉。
String.search(RegExp)只能找到第一個。
是否可以多次搜索?
例子
"Test".search(/./g)
// returns 0
我想要的是
"Test".search(/./g)
// returns [0, 1, 2, 3]
我在 DroidScript 中制作 RegExp 的東西。
var btn_h = app.CreateButton( "Highlight", 1 )
btn_h.SetOnTouch( highlight )
var edt_pt = app.CreateTextEdit( "/./g", 1 )
var edt_tx = app.CreateTextEdit( "Text", 1, 0.5 )
var txt_h = app.CreateText( "", 1, 0.5, "Multiline,Left,Html" )
function highlight()
{
var h = ""
var rg = edt_pt.GetText().split( "/", 1 )
var f = edt_pt.GetText().split( "/", 2 )
var pt = new RegExp( rg, f )
//if search returns array
edt_txt.GetText().search( pt ).forEach( function( i ) {
var i_ = 0
Array.from( edt_txt.GetText() ).forEach( function( char ) {
if(i_ == i) h = "<u>" char "</u>"
else h = char
i_
} )
} )
txt_h.SetHtml( h )
}
我想在與 RegExp 匹配的所有字符下劃線。是否可以?
uj5u.com熱心網友回復:
const regex = RegExp(/./, 'g');
const str = 'Test';
let match, indexes = [];
while (match = regex.exec(str))
indexes.push(match.index);
console.log(indexes);
uj5u.com熱心網友回復:
const regex = /./g;
const str = "Test";
const res = [...str.matchAll( regex ) ];
const index_list = res.map( item => item.index );
console.log( res );
console.log( index_list );
Output:
[
0: ['T', index: 0, input: 'Test', groups: undefined]
1: ['e', index: 1, input: 'Test', groups: undefined]
2: ['s', index: 2, input: 'Test', groups: undefined]
3: ['t', index: 3, input: 'Test', groups: undefined]
]
[0, 1, 2, 3]
這是你想要的嗎?
uj5u.com熱心網友回復:
據我所知,沒有官方的方法可以做到這一點,但是您可以使用 matchAll 和一些處理來模擬這一點
[..."Test".matchAll(/./g)].map((match) => {return match.index}) // [ 0, 1, 2, 3 ]
說明:matchAll 匹配腳本中的所有正則運算式,并為您提供匹配字串及其索引,然后我們使用 map 僅取回索引(作為搜索函式回傳的內容)
如果你想要一個簡寫函式,你可以把它寫在原型中
String.prototype.searchAll = function(regex) {
return [...this.matchAll(regex)].map((match) => {return match.index});
}
// then use it
"Test".searchAll(/./g) // [ 0, 1, 2, 3 ]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/418254.html
標籤:
上一篇:使用JS顯示計算的HTML輸出
