Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

javascript - 在一个替换呼叫中替换多个字符(Replace multiple characters in one replace call)

Very simple little question, but I don't quite understand how to do it.(非常简单的小问题,但我不太明白该怎么做。)

I need to replace every instance of '_' with a space, and every instance of '#' with nothing/empty.(我需要用空格替换'_'的每个实例,并且'#'的每个实例都没有/空。) var string = '#Please send_an_information_pack_to_the_following_address:'; I've tried this:(我试过这个:) string.replace('#','').replace('_', ' '); I don't really chaining commands like this, but is there another way to do it in one?(我不是真的链接这样的命令,但还有另一种方法可以做到这一点吗?)   ask by Shannon Hochkins translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the OR operator ( | ):(使用OR运算符( | ):)

var str = '#this #is__ __#a test###__'; str.replace(/#|_/g,''); // result: "this is a test" You could also use a character class:(您还可以使用字符类:) str.replace(/[#_]/g,''); Fiddle(小提琴) If you want to replace the hash with one thing and the underscore with another, then you will just have to chain.(如果你想用一个东西替换散列而用另一个东西替换下划线,那么你只需要链接。) However, you could add a prototype:(但是,您可以添加原型:) String.prototype.allReplace = function(obj) { var retStr = this; for (var x in obj) { retStr = retStr.replace(new RegExp(x, 'g'), obj[x]); } return retStr; }; console.log('aabbaabbcc'.allReplace({'a': 'h', 'b': 'o'})); // console.log 'hhoohhoocc'; Why not chain, though?(为什么不连锁?) I see nothing wrong with that.(我认为没有错。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...