let message ="hello https://ggogle.com parul https://yahoo.com and http://web.com";
let url=["https://ggogle.com", "https://yahoo.com", "http://web.com"];
I want to put text "***" in place of all url found in the message array from url array.
Tried this way -
let message = "hello https://ggogle.com parul https://yahoo.com and http://web.com";
let url = ["https://ggogle.com", "https://yahoo.com", "http://web.com"];
const replace = url.map(item => {
let indexes = message.indexOf(item);
let output = message.replaceAt(indexes, "***")
})
Error-message.replace is not a function,also if the logic is correct? Thanks!
1) You can easily achive the result using reduce
let message =
"hello https://ggogle.com parul https://yahoo.com and http://web.com";
let url = ["https://ggogle.com", "https://yahoo.com", "http://web.com"];
const result = url.reduce((msg, str) => msg.replace(new RegExp(str, "g"), "***"), message);
console.log(result);
2) You can also achieve the solution with forEach loop
let message =
"hello https://ggogle.com parul https://yahoo.com and http://web.com";
let url = ["https://ggogle.com", "https://yahoo.com", "http://web.com"];
url.forEach((s) => (message = message.replace(new RegExp(s, "g"), "***")));
console.log(message);
3) Using replace
let message =
"hello https://ggogle.com parul https://yahoo.com and http://web.com";
let url = ["https://ggogle.com", "https://yahoo.com", "http://web.com"];
const result = url.reduce((msg, str) => {
while (msg.indexOf(str) !== -1) msg = msg.replace(str, "***");
return msg;
}, message);
console.log(result);
The error is correct. replaceAt isn't a function, you're gonna have to use something like string substr() and then add your string inside, unless you think the string replace() method is good for your situation. I don't know enough about your case to decide.
This question might be useful, but make sure you actually add in the "***" after you cut out part of the string.
If I understood you correctly, you can just use replace instead of replaceAt.
For example:
let message = "hello https://ggogle.com parul https://yahoo.com and http://web.com";
let url = ["https://ggogle.com", "https://yahoo.com", "http://web.com"];
const replace = url.map(item => {
message = message.replace(item, "***")
})
console.log(message);