0

I need to develop a function in javascript that escapes some chars and then returns the cleaner string.

for example I need to prefix all those chars:

^ * +  ?  [  ]

by \

from:

this is a [string] that ^ contains some ? chars 

To

this is a \\[string\\] that \\^ contains some \\? chars 

Best regards

elementzero23
  • 1,389
  • 2
  • 16
  • 38
Amine Hatim
  • 237
  • 2
  • 7
  • 19
  • you mean echap or escape ?? – Hiren Jungi Jan 25 '17 at 13:03
  • This is not really a duplicate, it actually asks for a javascript function to escape JQL (jira query language) strings. See @Amine's comment below. I would suggest adding "jql" and "jira" as labels to the question. – cipak Oct 12 '18 at 19:07

1 Answers1

2

You can use a REGEX to do so:

'asdas^asdas [asd]'.replace(/([\^\*\+\?\[\]])/g, '\\$1')

Explanation:

  • ( : captures a group
  • [ : any of those
  • \^\*\+\?\[\] : all the chars you want, escaped
  • .replace : replace those who match (any of the chars you choose, save capturing group
  • $1 the first capturing group, prefixed by
  • // a single slash, escaped
Luan Nico
  • 5,376
  • 2
  • 30
  • 60
  • Thanks Luan I tried your regex But it return **asdas\^asdas \[asd\]** – Amine Hatim Jan 25 '17 at 13:09
  • Here it returns `"asdas\^asdas \[asd\]"`. I'm trying on chrome console and node v6.4.0. If you want double slashes, use quadruple slashes (escaped) in the replace part (`'\\\\$1'`). Are you sure the brackets are not escaped? What exact code are you running? – Luan Nico Jan 25 '17 at 13:11
  • I tried this it works **'asdas^asdas [asd]'.replace(/([\^\*\+\?\[\]])/g, '\\\\$1')** – Amine Hatim Jan 25 '17 at 13:12
  • Oh, you probably forgot the *g*. The *g* makes it global, that is, replace every occurrence, otherwise it will just do the first. – Luan Nico Jan 25 '17 at 13:12
  • I need to make Jira JQL request and there is some reserved characters which I need to escape theme – Amine Hatim Jan 25 '17 at 13:14
  • You need to escape every char (well, not every, but you can escape every one to be sure). If you want these chars `^*+?[]`, use `\^\*\+\?\[\]` (single slash before each). – Luan Nico Jan 25 '17 at 13:14
  • Thanks @Luna it works – Amine Hatim Jan 25 '17 at 13:23