0

I have an array full of names and am trying to get rid of any " ' " symbols because I am pulling the array in to a SQL statement and the " ' " is messing up my query.

My thought was to use replace but I have been messing around with it and it doesn't seem to be working. Any thoughts?

var names = ["Ben Smith", "Richard Brown", "Michael O'Donnell"]

for(var z = 0; z<names.length; z++){
    if(names[z].includes("'")){
        names[z].replace("'", "")
    }
}   

return names
D. Fowler
  • 5
  • 2
  • what is your expected result? – DecPK Jun 18 '21 at 11:44
  • @decpk the same array but with the ' removed from O'Donnell – D. Fowler Jun 18 '21 at 11:45
  • 1
    `names[z] = names[z].replace("'", "")` Note: `replace()` method returns a new string. Read docs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace – Satpal Jun 18 '21 at 11:46
  • 1
    What if I say my name is Robert");DROP TABLE students;--? You should use a library that includes escaping for sql statements. – Charlie Bamford Jun 18 '21 at 11:48
  • 1
    Two other things to be aware of: 1. When you use a string instead of a regular expression as the search term, only the **first** occurrence is replaced. 2. People named "O'Donnell" (and similar) don't take kindly to having their names misspelled "ODonnell" and such. – T.J. Crowder Jun 18 '21 at 11:48
  • 1
    Removing `'`' is **not** making the data safe for SQL. [Let me introduce you to my friend Bobby...](https://bobby-tables.com) – T.J. Crowder Jun 18 '21 at 11:49
  • 1
    You may also want to read up on [Prepared Statements](https://en.wikipedia.org/wiki/Prepared_statement), as they also protect against SQL Injection (I think). – Oskar Grosser Jun 18 '21 at 11:50
  • ```js const regex = /'/g; return names.map(n => n.replace(regex," ")) ``` – Bataklik Jun 18 '21 at 11:55

1 Answers1

0

You need to assign the value after replacement to array

names[z] = names[z].replace("'", "");

But you should use which replaces all occuring of '

names[z] = names[z].replace(/'/g, "");

function modifyNames() {
  var names = ["Ben Smith", "Richard Brown", "Michael O'Donnell"];

  for (var z = 0; z < names.length; z++) {
    if (names[z].includes("'")) {
      names[z] = names[z].replace("'", "");
    }
  }

  return names;
}


console.log(modifyNames());
DecPK
  • 24,537
  • 6
  • 26
  • 42