我需要将'_'的每个实例替换为一个空格,并将'#'的每个实例替换为无/空。
var string = '#Please send_an_information_pack_to_the_following_address:';
我试过了:
string.replace('#','').replace('_', ' ');
我真的不喜欢这样的链接命令。有没有另一种方法可以一次性完成?
我需要将'_'的每个实例替换为一个空格,并将'#'的每个实例替换为无/空。
var string = '#Please send_an_information_pack_to_the_following_address:';
我试过了:
string.replace('#','').replace('_', ' ');
我真的不喜欢这样的链接命令。有没有另一种方法可以一次性完成?
在正则表达式上指定/g (global)标志来替换所有匹配项,而不仅仅是第一个:
string.replace(/_/g, ' ').replace(/#/g, '')
要用一种东西替换一个字符,用另一种东西替换另一个字符,你真的不能避免需要两个单独的调用来替换。你可以把它抽象成一个函数,就像门把手做的那样,尽管我可能会让它把一个对象的旧/新作为键/值对,而不是一个平面数组。
使用OR运算符(|):
Var STR = '#this #is__ __#a test###__'; console.log ( Str.replace (/#|_/g, ") // "this is a test" )
你也可以使用字符类:
str.replace(/[#_]/g,'');
小提琴
如果你想用一个东西替换散列,用另一个东西替换下划线,那么你只需要链
函数allReplace(str, obj) { For (const x in obj) { str = str.replace(new RegExp(x, 'g'), obj[x]); } 返回str; }; console.log ( allReplace (abcd-abcd, {' a ': ' h ', ' b ': ' o ' } ) // ' hocd-hocd” );
为什么不加链子呢?我看不出这有什么不对。
还可以将RegExp对象传递给replace方法,如
var regexUnderscore = new RegExp("_", "g"); //indicates global match
var regexHash = new RegExp("#", "g");
string.replace(regexHash, "").replace(regexUnderscore, " ");
Javascript RegExp
捆绑很酷,为什么要抛弃它呢?
不管怎样,这里有一个替换的另一个选项:
string.replace(/#|_/g,function(match) {return (match=="#")?"":" ";})
如果匹配==“#”,则替换将选择“”,如果不匹配则选择“”。
对于一个更通用的解决方案,你可以将替换字符串存储在一个对象中:
var replaceChars={ "#":"" , "_":" " };
string.replace(/#|_/g,function(match) {return replaceChars[match];})
这里有一个不需要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;
}
你也可以试试这个:
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指要查找的文本,replace指要替换的文本
这将取代不区分大小写的字符。否则,只需根据需要更改Regex标志。对于区分大小写的替换:
new RegExp(find[i], 'g')
如果你想替换多个字符,你可以调用String.prototype.replace(),替换参数是为每个匹配调用的函数。您所需要的只是一个表示将在该函数中使用的字符映射的对象。
例如,如果你想用x替换a,用y替换b,用z替换c,你可以这样做:
Const chars = { a:“x”, b:‘y’, “c”:“z” }; Let s = ' 234abc567bbbac '; S = S .replace(/[abc]/g, m => chars[m]); console.log(年代);
输出:234xyz567yyyyxz
yourstring = '#请send_an_information_pack_to_the_following_address:';
将“#”替换为“”,将“_”替换为空格
var newstring1 = yourstring.split('#').join('');
var newstring2 = newstring1.split('_').join(' ');
Newstring2是你的结果
请尝试:
更换多管柱 Var STR = "http://www.abc.xyz.com"; STR = STR .replace(/http:|www|.com/g, ");//str是"//.abc.xyz" 替换多字符 Var STR = "a.b.c.d,e,f,g,h"; STR = STR .replace(/[。) / g,”);//str是"abcdefgh";
好运!
我不知道这有多大帮助,但我想从我的字符串中删除<b>和</b>
所以我用了
mystring.replace('<b>',' ').replace('</b>','');
所以基本上,如果你想要减少有限数量的字符,不浪费时间,这将是有用的。
第二次更新
我开发了以下功能用于生产,也许它可以帮助其他人。它基本上是原生的replaceAll Javascript函数的循环,它没有使用regex:
function replaceMultiple(text, characters){
for (const [i, each] of characters.entries()) {
const previousChar = Object.keys(each);
const newChar = Object.values(each);
text = text.replaceAll(previousChar, newChar);
}
return text
}
用法非常简单。下面是使用OP的例子的样子:
const text = '#Please send_an_information_pack_to_the_following_address:';
const characters = [
{
"#":""
},
{
"_":" "
},
]
const result = replaceMultiple(text, characters);
console.log(result); //'Please send an information pack to the following address:'
更新
现在可以在本地使用replaceAll。
过时的回答
下面是使用字符串原型的另一个版本。享受吧!
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"
这里是一个使用“reduce”多重替换函数的“安全HTML”函数(该函数将每个替换应用于整个字符串,因此替换之间的依赖关系非常重要)。
// Test:
document.write(SafeHTML('<div>\n\
x</div>'));
function SafeHTML(str)
{
const replacements = [
{'&':'&'},
{'<':'<'},
{'>':'>'},
{'"':'"'},
{"'":'''},
{'`':'`'},
{'\n':'<br>'},
{' ':' '}
];
return replaceManyStr(replacements,str);
} // HTMLToSafeHTML
function replaceManyStr(replacements,str)
{
return replacements.reduce((accum,t) => accum.replace(new RegExp(Object.keys(t)[0],'g'),t[Object.keys(t)[0]]),str);
}
String.prototype.replaceAll =函数(obj keydata =“关键”){ const键= keydata.split(关键); 返回Object.entries (obj) .reduce((,(关键,val)) = > a.replace(新的正则表达式(“${键[0]}${关键}${键[1]}',' g '), val),) } Const data='隐藏dv SDC sd {yathin} {ok}' console.log (data.replaceAll ({yathin: 12,好的:“嗨”},{关键}))
对于什么都不替换,tckmn的答案是最好的。
如果你需要替换对应匹配的特定字符串,下面是Voicu和Christophe回答的一个变体,避免重复被匹配的内容,这样你就不必记得在两个地方添加新的匹配:
const replacements = {
'’': "'",
'“': '"',
'”': '"',
'—': '---',
'–': '--',
};
const replacement_regex = new RegExp(Object
.keys(replacements)
// escape any regex literals found in the replacement keys:
.map(e => e.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
.join('|')
, 'g');
return text.replace(replacement_regex, e => replacements[e]);
可以用一个简单的正则表达式替换多个子字符串。 例如,我们想要将数字(123)456-7890转换为1234567890,我们可以这样做。
var a = '(123) 456-7890';
var b = a.replace(/[() -]/g, '');
console.log(b); // results 1234567890
我们可以在[]之间传递要替换的子字符串,而要替换的字符串应该作为第二个参数传递给replace函数。
这适用于意第绪语的其他角色,如NEKUDES
var string = "נׂקֹוַדֹּוֶת";
var string_norm = string.replace(/[ְֱֲֳִֵֶַָֹֹּׁׂ]/g, '');
document.getElementById("demo").innerHTML = (string_norm);
不知道为什么还没有人提供这个解决方案,但我发现它非常有效:
var string = '#Please send_an_information_pack_to_the_following_address:'
var placeholders = [
"_": " ",
"#": ""
]
for(var placeholder in placeholders){
while(string.indexOf(placeholder) > -1) {
string = string.replace(placeholder, placeholders[placeholder])
}
}
你可以添加任何你喜欢的占位符,而不必更新你的函数。简单!
一个函数和一个原型函数。
String.prototype.replaceAll = function (search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'gi'), replacement);
};
var map = {
'&': 'and ',
'[?]': '',
'/': '',
'#': '',
// '|': '#65 ',
// '[\]': '#66 ',
// '\\': '#67 ',
// '^': '#68 ',
'[?&]': ''
};
var map2 = [
{'&': 'and '},
{'[?]': ''},
{'/': ''},
{'#': ''},
{'[?&]': ''}
];
name = replaceAll2(name, map2);
name = replaceAll(name, map);
function replaceAll2(str, map) {
return replaceManyStr(map, str);
}
function replaceManyStr(replacements, str) {
return replacements.reduce((accum, t) => accum.replace(new RegExp(Object.keys(t)[0], 'g'), t[Object.keys(t)[0]]), str);
}
如果只是使用if else语句的简写呢?使它成为一行程序。
const betterWriting = string.replace(/[#_]/gi , d => d === '#' ? '' : ' ' );
或者选择对我来说很好 示例let sample_string = <strong>一些带有html标签的单词</strong> |。需要删除强标签和“|”文本。 代码如下:= sample_string.replace(/\|(.*)|<strong>|<\/strong>/g,"")