参考:
In javascript, how do you search an array for a substring match
这里给出的解决方案是通用的,不像solution 4556343#4556343,它需要先前的解析来识别join()所使用的字符串,它不是任何数组字符串的组成部分。
另外,在该代码中/!id-[^!]*/ 更正确,/![^!]*id-[^!]*/ 适合问题参数:
- “搜索数组...”(字符串或数字,而不是函数、数组、对象等)
- “只匹配部分字符串”(匹配可以在任何地方)
- “返回 ... 匹配的 ... 元素”(单数,而不是 ALL,如“... the ... elementS”)
- “带有完整的字符串”(包括引号)
... NetScape / FireFox 解决方案(见下文JSON 解决方案):
javascript: /* "one-liner" statement solution */
alert(
["x'!x'\"id-2",'\' "id-1 "', "item","thing","id-3-text","class" ] .
toSource() . match( new RegExp(
'[^\\\\]("([^"]|\\\\")*' + 'id-' + '([^"]|\\\\")*[^\\\\]")' ) ) [1]
);
或
javascript:
ID = 'id-' ;
QS = '([^"]|\\\\")*' ; /* only strings with escaped double quotes */
RE = '[^\\\\]("' +QS+ ID +QS+ '[^\\\\]")' ;/* escaper of escaper of escaper */
RE = new RegExp( RE ) ;
RA = ["x'!x'\"id-2",'\' "id-1 "', "item","thing","id-3-text","class" ] ;
alert(RA.toSource().match(RE)[1]) ;
显示"x'!x'\"id-2"。
也许突袭阵列以找到所有匹配项是“更干净”。
/* literally (? backslash star escape quotes it!) not true, it has this one v */
javascript: /* purely functional - it has no ... =! */
RA = ["x'!x'\"id-2",'\' "id-1 "', "item","thing","id-3-text","class" ] ;
function findInRA(ra,id){
ra.unshift(void 0) ; /* cheat the [" */
return ra . toSource() . match( new RegExp(
'[^\\\\]"' + '([^"]|\\\\")*' + id + '([^"]|\\\\")*' + '[^\\\\]"' ,
'g' ) ) ;
}
alert( findInRA( RA, 'id-' ) . join('\n\n') ) ;
显示:
"x'!x'\"id-2"
"' \"id-1 \""
“id-3-文本”
使用,JSON.stringify():
javascript: /* needs prefix cleaning */
RA = ["x'!x'\"id-2",'\' "id-1 "', "item","thing","id-3-text","class" ] ;
function findInRA(ra,id){
return JSON.stringify( ra ) . match( new RegExp(
'[^\\\\]"([^"]|\\\\")*' + id + '([^"]|\\\\")*[^\\\\]"' ,
'g' ) ) ;
}
alert( findInRA( RA, 'id-' ) . join('\n\n') ) ;
显示:
["x'!x'\"id-2"
"' \"id-1 \""
“id-3 文本”
皱纹:
- “未转义”的全局 RegExp 是
/[^\]"([^"]|\")*id-([^"]|\")*[^\]"/g,而 \ 可以从字面上找到。为了使([^"]|\")* 匹配所有" 转义为\" 的字符串,\ 本身必须转义为([^"]|\\")*。当这被引用为要与id- 连接的字符串时,每个\ 必须再次转义,因此([^"]|\\\\")*!
- 具有
\、*、"、...的搜索ID也必须通过.toSource()或JSON或...进行转义。
-
null 搜索结果应返回 ''(或 "",如包含 NO "! 的 EMPTY 字符串)或 [](适用于所有搜索)。
- 如果要将搜索结果合并到程序代码中进行进一步处理,则需要
eval(),如eval('['+findInRA(RA,ID).join(',')+']')。
----------------------------------------------- ----------------------------------
题外话:
突袭和逃跑?这段代码有冲突吗?
/* it has no ... =! */ 的符号学、语法和语义强调了引用文字冲突的转义。
“没有=”的意思是:
- “没有'='符号”,如
javascript:alert('\x3D')(不是!运行它,看看有没有!),
- “没有带有赋值运算符的javascript语句”,
- “不相等”与“任何其他代码都不相同”(以前的代码解决方案证明存在功能等价物),
- ...
也可以使用下面的立即模式 javascript 协议 URI 在另一个级别上进行引用。 (// 注释以新行结束(又名 nl,ctrl-J,LineFeed,ASCII 十进制 10,八进制 12,十六进制 A),由于插入 nl,通过按 Return 键调用 URI,因此需要引用。)
javascript:/* a comment */ alert('visible') ;
javascript:// a comment ; alert( 'not' ) this is all comment %0A;
javascript:// a comment %0A alert('visible but %\0A is wrong ') // X %0A
javascript:// a comment %0A alert('visible but %'+'0A is a pain to type') ;
注意:剪切并粘贴任何 javascript: 行作为即时模式 URI(至少,最多?,在 FireFox 中)以使用第一个 javascript: 作为 URI 方案或协议,其余作为 JS 标签。