我需要将'_'的每个实例替换为一个空格,并将'#'的每个实例替换为无/空。
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('_', ' ');
我真的不喜欢这样的链接命令。有没有另一种方法可以一次性完成?
当前回答
不知道为什么还没有人提供这个解决方案,但我发现它非常有效:
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])
}
}
你可以添加任何你喜欢的占位符,而不必更新你的函数。简单!
其他回答
第二次更新
我开发了以下功能用于生产,也许它可以帮助其他人。它基本上是原生的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"
我不知道这有多大帮助,但我想从我的字符串中删除<b>和</b>
所以我用了
mystring.replace('<b>',' ').replace('</b>','');
所以基本上,如果你想要减少有限数量的字符,不浪费时间,这将是有用的。
请尝试:
更换多管柱 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";
好运!
yourstring = '#请send_an_information_pack_to_the_following_address:';
将“#”替换为“”,将“_”替换为空格
var newstring1 = yourstring.split('#').join('');
var newstring2 = newstring1.split('_').join(' ');
Newstring2是你的结果
如果只是使用if else语句的简写呢?使它成为一行程序。
const betterWriting = string.replace(/[#_]/gi , d => d === '#' ? '' : ' ' );