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

var string = '#Please send_an_information_pack_to_the_following_address:';

我试过了:

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

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


当前回答

你可以试试这个:

str.replace(/[.#]/g, 'replacechar');

这将用你的replacechar !

其他回答

可以用一个简单的正则表达式替换多个子字符串。 例如,我们想要将数字(123)456-7890转换为1234567890,我们可以这样做。

var a = '(123) 456-7890';
var b = a.replace(/[() -]/g, '');
console.log(b); // results 1234567890

我们可以在[]之间传递要替换的子字符串,而要替换的字符串应该作为第二个参数传递给replace函数。

使用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” );

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

请尝试:

更换多管柱 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";

好运!

如果只是使用if else语句的简写呢?使它成为一行程序。

const betterWriting = string.replace(/[#_]/gi , d => d === '#' ? '' : ' ' );

这里是一个使用“reduce”多重替换函数的“安全HTML”函数(该函数将每个替换应用于整个字符串,因此替换之间的依赖关系非常重要)。

// Test:
document.write(SafeHTML('<div>\n\
    x</div>'));

function SafeHTML(str)
    {
    const replacements = [
        {'&':'&amp;'},
        {'<':'&lt;'},
        {'>':'&gt;'},
        {'"':'&quot;'},
        {"'":'&apos;'},
        {'`':'&grave;'},
        {'\n':'<br>'},
        {' ':'&nbsp;'}
        ];
    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);
    }