jQuery 在一次替换调用中替换多个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16576983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace multiple characters in one replace call
提问by Shannon Hochkins
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:';
var string = '#Please send_an_information_pack_to_the_following_address:';
I've tried this:
我试过这个:
string.replace('#','').replace('_', ' ');
string.replace('#','').replace('_', ' ');
I don't really like chaining commands like this. Is there another way to do it in one?
我真的不喜欢像这样链接命令。有没有另一种方法可以做到这一点?
回答by Doorknob
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.
不过,为什么不连锁呢?我看不出有什么问题。
回答by Christophe
Chaining is cool, why dismiss it?
链接很酷,为什么要忽略它?
Anyway, here is another option in one replace:
无论如何,这是一次替换的另一种选择:
string.replace(/#|_/g,function(match) {return (match=="#")?"":" ";})
The replace will choose "" if match=="#", " " if not.
如果匹配==“#”,则替换将选择“”,否则将选择“”。
[Update] For a more generic solution, you could store your replacement strings in an object:
[更新] 对于更通用的解决方案,您可以将替换字符串存储在一个对象中:
var replaceChars={ "#":"" , "_":" " };
string.replace(/#|_/g,function(match) {return replaceChars[match];})
回答by Voicu
If you want to replace multiple characters you can call the String.prototype.replace()
with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping which you will use in that function.
如果你想替换多个字符,你可以调用String.prototype.replace()
替换参数是一个为每个匹配调用的函数。您所需要的只是一个表示您将在该函数中使用的字符映射的对象。
For example, if you want a
replaced with x
, b
with y
and c
with z
, you can do something like this:
例如,如果你想a
与更换x
,b
与y
和c
与z
,你可以这样做:
var chars = {'a':'x','b':'y','c':'z'};
var s = '234abc567bbbbac';
s = s.replace(/[abc]/g, m => chars[m]);
console.log(s);
Output: 234xyz567yyyyxz
输出:234xyz567yyyyxz
回答by Mark Reed
Specify the /g
(global) flag on the regular expression to replace all matches instead of just the first:
/g
在正则表达式上指定(全局)标志以替换所有匹配项,而不仅仅是第一个:
string.replace(/_/g, ' ').replace(/#/g, '')
To replace one character with one thing and a different character with something else, you can't really get around needing two separate calls to replace
. You can abstract it into a function as Doorknob did, though I would probably have it take an object with old/new as key/value pairs instead of a flat array.
要将一个字符替换为一件事,而将不同的字符替换为另一件事,您真的无法绕过需要两次单独调用replace
. 您可以像 Doorknob 那样将其抽象为一个函数,但我可能会让它使用一个带有 old/new 的对象作为键/值对,而不是一个平面数组。
回答by Tapan Bala
You could also try this :
你也可以试试这个:
function replaceStr(str, find, replace) {
for (var i = 0; i < find.length; i++) {
str = str.replace(new RegExp(find[i], 'gi'), replace[i]);
}
return str;
}
var text = "#here_is_the_one#";
var find = ["#","_"];
var replace = ['',' '];
text = replaceStr(text, find, replace);
console.log(text);
find
refers to the text to be found and replace
to the text to be replaced with
find
指要查找replace
的文本和要替换的文本
This will be replacing case insensitive characters. To do otherway just change the Regex flags as required. Eg: for case sensitive replace :
这将替换不区分大小写的字符。要以其他方式做,只需根据需要更改正则表达式标志。例如:对于区分大小写的替换:
new RegExp(find[i], 'g')
回答by karim somai
You can just try this :
你可以试试这个:
str.replace(/[.#]/g, 'replacechar');
this will replace .,- and # with your replacechar !
这将用您的 replacechar 替换 .,- 和 # !
回答by Beejor
Here's a simple way to do it without RegEx.
You can prototype and/or cache things as desired.
这是一种无需 RegEx 的简单方法。
您可以根据需要制作原型和/或缓存内容。
// Example: translate( 'faded', 'abcdef', '123456' ) returns '61454'
function translate( s, sFrom, sTo ){
for ( var out = '', i = 0; i < s.length; i++ ){
out += sTo.charAt( sFrom.indexOf( s.charAt(i) ));
}
return out;
}
回答by Tran Hung
Please try:
请尝试:
replace multi string
var str = "http://www.abc.xyz.com"; str = str.replace(/http:|www|.com/g, ''); //str is "//.abc.xyz"
replace multi chars
var str = "a.b.c.d,e,f,g,h"; str = str.replace(/[.,]/g, ''); //str is "abcdefgh";
替换多字符串
var str = "http://www.abc.xyz.com"; str = str.replace(/http:|www|.com/g, ''); //str is "//.abc.xyz"
替换多个字符
var str = "a.b.c.d,e,f,g,h"; str = str.replace(/[.,]/g, ''); //str is "abcdefgh";
Good luck!
祝你好运!
回答by Hafsul Maru
yourstring = '#Please send_an_information_pack_to_the_following_address:';
yourstring = '#请发送_an_information_pack_to_the_following_address:';
replace '#' with '' and replace '_' with a space
用 '' 替换 '#' 并用空格替换 '_'
var newstring1 = yourstring.split('#').join('');
var newstring2 = newstring1.split('_').join(' ');
newstring2 is your result
newstring2 是你的结果
回答by Diego Fortes
Here is another version using String Prototype. Enjoy!
这是另一个使用字符串原型的版本。享受!
String.prototype.replaceAll = function(obj) {
let finalString = '';
let word = this;
for (let each of word){
for (const o in obj){
const value = obj[o];
if (each == o){
each = value;
}
}
finalString += each;
}
return finalString;
};
'abc'.replaceAll({'a':'x', 'b':'y'}); //"xyc"