简体   繁体   中英

javascript regex … how to escape hyphen

how to escape a hyphen in a replace statement

var lvs = "ui-btn ui-btn-up-XXX  ui-li ui-li-has-icon ui-btn-hover-e ui-btn-up-ZZZ" ;

var lvs = lvs.replace(/\bui-btn-up-[^\b]*?\b/gi , "" ) ;
alert( lvs);

I have tried many variations of forwards and backwards slashes

I think you are making it too complicated with the word break characters ( \\b ). Would this not work for what you are trying to do?

var lvs = lvs.replace(/ui-btn-up(-\w+)?/gi, "");

That is also assuming that you want to remove a value of ui-btn-up . If not, then use:

var lvs = lvs.replace(/ui-btn-up-\w+/gi, "");

您想这样做吗?

var lvs = lvs.replace(/\sui-btn-up-\S+\s*?/gi , "" ) ;

this works ok for me :-

lvs = "ui-btn ui-btn-up-XXX  ui-li ui-li-has-icon ui-btn-hover-e ui-btn-up-ZZZ" ;
var lvs = lvs.replace(/\bui-btn-up-\w*\s*/gi , "" ) ;
alert( lvs);

http://jsfiddle.net/keith_nicholas/6KA9T/

You don't have to escape - .

'sonia-b-cat'.replace(/a-b-c/, '123') // 'sonia123at'

Only when it's in a character class do you need to escape it with a backslash

'z-z'.replace(/[abc\-]/, '123') // 'z123z'

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