我需要将'_'的每个实例替换为一个空格,并将'#'的每个实例替换为无/空。

var string = '#Please send_an_information_pack_to_the_following_address:';

我试过了:

string.replace('#','').replace('_', ' ');

我真的不喜欢这样的链接命令。有没有另一种方法可以一次性完成?


当前回答

或者选择对我来说很好 示例let sample_string = <strong>一些带有html标签的单词</strong> |。需要删除强标签和“|”文本。 代码如下:= sample_string.replace(/\|(.*)|<strong>|<\/strong>/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” );

为什么不加链子呢?我看不出这有什么不对。

这里有一个不需要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;
}

捆绑很酷,为什么要抛弃它呢?

不管怎样,这里有一个替换的另一个选项:

string.replace(/#|_/g,function(match) {return (match=="#")?"":" ";})

如果匹配==“#”,则替换将选择“”,如果不匹配则选择“”。

对于一个更通用的解决方案,你可以将替换字符串存储在一个对象中:

var replaceChars={ "#":"" , "_":" " };
string.replace(/#|_/g,function(match) {return replaceChars[match];})

yourstring = '#请send_an_information_pack_to_the_following_address:';

将“#”替换为“”,将“_”替换为空格

var newstring1 = yourstring.split('#').join('');
var newstring2 = newstring1.split('_').join(' ');

Newstring2是你的结果

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,好的:“嗨”},{关键}))