-3

I have a random string that comes from a data source that I do not control. My upstream system has a requirement for such IDs: "Field names must begin with a letter and can contain only letters, digits, or underscore ('_')".

How, in Typescript/Javascript (possibly, with lodash) can I replace all string symbols that is not a letter/digit/underscore to an underscore?

onkami
  • 8,791
  • 17
  • 90
  • 176
  • Did you try writing a regex, or something with lodash? Note that this mangling may lead to collisions, as more than one input string will have the same output. – jonrsharpe Sep 03 '20 at 10:45
  • Fair point about collisions, but i do not expect these in my use case, and the risk is far from critical – onkami Sep 03 '20 at 10:46
  • You can add your specific characters link this:- https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript – Vishal Nakum Sep 03 '20 at 10:48

1 Answers1

2
const input = '8~3m_E!P$m%S^wx_-';
input.replace(/[\W]/gm, '_');
// output: 8_3m_E_P_m_S_wx__

Note: This doesn't cover this part of the requirement: 'Field names must begin with a letter'. However, because you didn't ask about it specifically, I assumed you already had it covered.