简体   繁体   中英

Why this doesn't work?

var str="Hello World!"; 
var patt=/\x57/g;
var matched = str.match(patt);
document.write(matched.strike());

It seems that the problem is matched.strike() . With matched only it works. So why?

The .strike() method operates on strings and matched is an array. You must dereference the first match to see the correct output.

var str="Hello World!"; 
var patt=/\x57/g;
var matched = str.match(patt);
// Access first element of the matched array
document.write(matched[0].strike());

// Or via .pop() or .shift()
document.write(matched.pop().strike());
// or
document.write(matched.shift().strike());
// either returns "<strike>W</strike>"

The String.strike() method is nonstandard , and should not be relied upon for complete browser support.

The (very old) strike method is a String method. RegExp.match returns an Array which doesn't know a strike method.

Your code could be rewritten to:

var str = 'Hello World'.replace(/\x57/g,function(s){return s.strike();});
//=> Hello <strike>W</strike>orld

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM