Home > Net >  How to get exact pattern which has specific word by using Regex in javascript
How to get exact pattern which has specific word by using Regex in javascript

Time:03-19

I have a question for you. I write simple regex but it didn't work way that what I want.

My regex:

/^\bname\b="([^"]*)"$/

But it did not work. So I decided to change that regex to this:

/name="([^"]*)"$/

this is perfectly fine to me when I have just one match case. In other words, This is working fine this case:

let my_case = 'Content-Disposition: form-data; name="body"';
let result = my_case.match(/name="([^"]*)"$/);
console.log(result);

but when I change case string to like this:

let my_case = 'Content-Disposition: form-data; name="relatedFile"; filename="article_217605.pdf"';
let result = my_case.match(/name="([^"]*)"$/);
console.log(result);

Result be like:

[
  'name="article_217605.pdf"',
  'article_217605.pdf',
  index: 24,
  input: 'name="relatedFile"; filename="article_217605.pdf"',
  groups: undefined
]

I don't wanna this actually. I want to get (name="relatedFile") how to get this in this case? pls help me!

CodePudding user response:

  • Since it's a string
  • Instead of regex you can split and map element for this case

let somecase = 'Content-Disposition: form-data; name="relatedFile"; filename="article_217605.pdf"';

let res = somecase.split(";").map(ele => ele)[1];
console.log(res)
let sers = acase.split(";").find(ele => /([a-z]*)name=.*/g.test(ele));
sers

  • Using Regex

let somecase = 'Content-Disposition: form-data; name="relatedFile"; filename="article_217605.pdf"';

let res = somecase.split(";").find(ele => /([a-z]*)name=.*/g.test(ele));
console.log(res)

CodePudding user response:

I got exactly correct answer. By the way thank you to answering my question @The fourth bird.

His answer is:

/\bname="[^"]*"/

But it doesn't work well because result couldn't give me name value. So I change it little bit.

Correct perfect answer is:

/\bname="([^"]*)"/

thank you guys! I am really appreciate it.

  • Related