Home > Enterprise >  Ignore \n and \ in a string javascript
Ignore \n and \ in a string javascript

Time:02-15

Is it possible to ignore \n and \ in a string?

Here is my example, I have strings that I acquired automatically and some of them have \ and \n, the problem is that I want to replace them all in a file but when I'm matching them with regex the string I get from regex.match XX.Sp("\tS◄J_-D%\n", rv) is ignoring \ and \n, but the array that I have with values when comparing the values of regex return and string from array they do not match because the string taken from obj1 is transforming all \ and \n accordingly.

const obj1 = [{func: 'XX.Sp("\tSJ_-D%\n", rv)',
name: 'nameofthedes',
}]
  

EXAMPLE

function des(match) {
  const x = /\\|\n/g
  const nm = match.replace(x,'');

  for (var i in obj){
    if (i) {
      console.log(nm) // XX.Sp("tS◄J_-D%n", rv)
      console.log(i.replace(x,'')) //  XX.Sp(" S◄J_-D%", rv)
      console.log(i.replace(x,'') == nm) // false
    }
    
  }
  if (obj[match]) {
    console.log(obj[match])
    return `"${obj[match]}"`
  }
  return match
}

EDIT:

So the problem that I'm having is when using regex to match, it returns all the special characters escaped so that is why it is not matching, how can i prevent the regex match from doing it?

when matching with regex this string XX.Sp("\tSJ_-D%\n", rv) is becoming XX.Sp("\\tSJ_-D%\\n", rv) that is why I can't compare them.

CodePudding user response:

regex = /\\|\n/g
string.replace(regex,'');

'\\' for slash and '\n' for '\n' g flag matching all occurance. You can use replaceAll() but this is not very consistent for every JS engine

CodePudding user response:

The problem you have is that your regular expression /\\|\n/g is targetting the \ chracter first so the newline \n just becomes n.

You have also assumed that a single \ is valid in a string - it has special meaning and must always be followed by another character.

Note that there are 2 of these in your string \n and \t.

\n is the newline character and \t is the tab character. Notice the white space in some of your logging, it's a tab.

What you should be doing is removing both \t and \n with /\t|\n/g

const str = 'XX.Sp("\tSJ_-D%\n", rv)';
console.log(str);

/* outputs:
XX.Sp(" SJ_-D%
", rv)
*/

const fixed = str.replace(/\t|\n/g,'');

console.log(fixed);
/* outputs:
XX.Sp("SJ_-D%", rv)
*/

  • Related