0

I have an issue with JavaScript Regular Expression to Replace Escape Special Characters from String like for example 1)

var = test{test}/uk/london=?paris{},clients,vague>;

and I want to extract the result only in just this format = /uk/london so I only want /uk/london from the line above how do I code this in javascript?

smac89
  • 39,374
  • 15
  • 132
  • 179
jezza
  • 1
  • 1
  • 2
  • `var = test{test}/uk/london=?paris{},clients,vague>` is invalid – Muhammad Usman May 03 '18 at 14:57
  • Do you want to explicitly extract only `/uk/london` or are you looking for the pattern that consists of a slash followed by a word then another slash followed by another word? – smac89 May 03 '18 at 14:59
  • Do you always want everything from the first "/" to the first "=" ? – Andrew Morton May 03 '18 at 14:59
  • `let str = 'test{test}/uk/london=?paris{},clients,vague>'; str.match(/\/(.*)=/)[1]` – junvar May 03 '18 at 15:11
  • yes explicitly extract like from /uk/london to just before = sign – jezza May 03 '18 at 15:18
  • @smac89 yes explicitly extract like from /uk/london to just before = sign – jezza May 03 '18 at 15:18
  • api/v1/Projectlook/GetAllAnswers?clientCode={clientCode}&username={username}&password={password}&httpsessionid={httpsessionid} ..... From this line I Only want Projectlook/GetAllAnswers @smac89 – jezza May 03 '18 at 15:20
  • api/v1/Projectlook/GetAllAnswers?clientCode={clientCode}&username={username}&password={password}&httpsessionid={httpsessionid} ..... From this line I Only want Projectlook/GetAllAnswers @AndrewMorton – jezza May 03 '18 at 15:22
  • api/v1/Projectlook/GetAllAnswers?clientCode={clientCode}&username={username}&password={password}&httpsessionid={httpsessionid} ..... From this line I Only want Projectlook/GetAllAnswers @junvar – jezza May 03 '18 at 15:23
  • So it seems you want the pattern, not the string. – smac89 May 03 '18 at 17:43

1 Answers1

0
var s = "test{test}/uk/london=?paris{},clients,vague>";
var re = /(\/.*)=/;
var t = re.exec(s)[1];
console.log(t);

outputs to the console:

/uk/london

The part in parentheses is captured in a group.
That group starts with a "/" (which has to be escaped by the "\") and the rest of it can be any character "." any number of times "*".
The ".*" is stopped by the requirement to match "=".

exec executes the regex, and [1] gets the first group.

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
  • Hi I'm, getting an error called cannot read property '1' of null any help on this as its pointing to var t= this line ? @AndrewMorton var jsonData = JSON.parse(responseBody); var length = jsonData.length; for(var i=0;i – jezza May 04 '18 at 08:37
  • @jezza That means that there was not a match. You can [Check whether a string matches a regex in JS](https://stackoverflow.com/a/6603043/1115360) to see if there will be a `[1]` item. – Andrew Morton May 04 '18 at 08:45