with javascript, how to make string only have letters, numbers, and period. Remove all other characters

86 views Asked by At

What to edit in the js below, so this file name: old_file_name = this8_ file-name=44.jpg
becomes this: new_file_name = this8filename44.jpg

Replace any character unless it is a letter, number, or . with '' (ie. nothing)

var old_file_name = file.upload.filename;
new_file_name = old_file_name.replace(/^[ A-Za-z0-9.\s]*$/i, '');
console.log("file name is:"+new_file_name);
console.log("original file name is:"+old_file_name);
2

There are 2 answers

0
Mister Jojo On BEST ANSWER

simply this :

const cleanFileName = fn => fn.replace(/[^a-z0-9.]/ig, '')
  ;
let old_file_name = "this8_ file-Name=44.jpg"
  , new_file_name = cleanFileName( old_file_name )
  ;
console.log( old_file_name )  // -> this8_ file-Name=44.jpg
console.log( new_file_name )  // -> this8fileName44.jpg

0
Oliver Cavanagh On
new_file_name = old_file_name.replace(^[A-Za-z0-9_.]+$, '');

This will check from start to finish if it matched one or more of the conditions.