0
Custom Replace function
I am trying to replace a character (s) in a string without using inbuilt replace function. Why won't this replace : let a = "gr#po#"; function repl(word, char, re){ let em = ""; for (let i = 0; i < word.length; i++) { if (word[i] == char){ word[i] = re; // you can directly change an elenent in an array but its not working here } em += word[i]; } return em; } output = repl(a, '#', '*'); console.log(output); // gr#po#
6 Réponses
+ 6
look at "word" – log it to console: it is not an array of individual characters.
to split a string, use
word.split("");
but why don't you just do
em += re
instead?
+ 3
Mac Anthony
There is an excellent method of replacing characters and it sounds in plain text in your question...😎
console.log(a.replace(/#/g,'*'));
+ 2
word is a string
i iterated through the string to get each individual character and there is an if statement which points to a specific index that falls under the condition
i am working on my algorithm i dont want to depend on any function to solve this
if i use em = +re
it means that i am only appending the replacement character and the output would be **
Lisa do you have an approach to this without using an inbuilt function
+ 2
word is a string. it is not an array. hence, you cannot simply replace a character by index.
you are returning "em" anyway? why do you return "em" if you don't want it?
for
em += re
you just need to iterate the string itself...
+ 2
Mac Anthony if you don't want to use the built-in functions, then change your condition to this and everything will work:
if(word[i] == char){
em += re;
}else{
em += word[i];
}
P.S: "The string itself cannot be changed, it can only be added, since it is not stored as an array, as it is done, for example, in python."
+ 1
Lisa you are right. word is a string which cant be changed directly
so i splitted it into an array before iteration it worked. thank so much
let a = "gr#po#";
function repl(word, char, re){
let em = "";
arr = word.split("");
for (let i = 0; i < arr.length; i++) {
if (arr[i] == char){
arr[i] = re; // you can directly change an element since its an array
}
em += arr[i];
}
return em;
}
output = repl(a, '#', '*');
console.log(output); // gr*po*