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#

12th Jan 2024, 3:39 PM
Mac Anthony
Mac Anthony - avatar
6 Respostas
+ 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?
12th Jan 2024, 4:20 PM
Lisa
Lisa - avatar
+ 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,'*'));
12th Jan 2024, 7:38 PM
Solo
Solo - avatar
+ 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
12th Jan 2024, 7:31 PM
Mac Anthony
Mac Anthony - avatar
+ 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...
12th Jan 2024, 7:34 PM
Lisa
Lisa - avatar
+ 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."
12th Jan 2024, 7:59 PM
Solo
Solo - avatar
+ 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*
12th Jan 2024, 8:20 PM
Mac Anthony
Mac Anthony - avatar