'How to get exact pattern which has specific word by using Regex in javascript

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!



Solution 1:[1]

The pattern ^\bname\b="([^"]*)"$ does not match as it asserts the start and the end of the string. In a pattern like this, the word boundaries \b are also implicit and can be omitted from the pattern.

This pattern that you tried name="([^"]*)"$ will allow a partial match starting with name and then will only match as it can assert the end of the string and will give you the wrong match.

If you would start that pattern with a word boundary, there will still be no match because it will then not allow a partial match anymore.

You could start the match with a word boundary and then capture in group 1 the value between double quotes without using any of the other anchors.

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

See the match on regex101.

Solution 2:[2]

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.

Solution 3:[3]

  • 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)
  • Using Regex

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

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 The fourth bird
Solution 2 Nyamkhuu Buyanjargal
Solution 3