Santosh S Kumar
Santosh S Kumar

Reputation: 479

Return full string if partial string is found Javascript/Jquery

Unable to retrieve full string if partially matched.

Example:

src = 'The expression $ a{\color{blue}{x}}^2 + b{\color{blue}{x}} + c$ is said to be quadratic when TAtrimg001a.svg is \neq 0$'

search for "svg" > should return TAtrimg001a.svg

I am trying to search and find the string "svg". If the "svg" exists then it should return TAtrimg001a.svg not just its location or the word svg itself but the complete svg filename.

In reply to a comment...

I tried finding the match in following differenet ways, but they do really work for my requirment, example:

var res = str.match(/svg/ig);
var res = str.search("svg");
var res = str.indexOf( "svg" )

Upvotes: 0

Views: 1525

Answers (2)

P.S.
P.S.

Reputation: 16384

In ES6 you can do something like const result = str.endsWith(".svg") ? str : null;, which will store in result variable full file name (if it ends with ".svg" part, in other words, has svg format), or null (if it doesn't):

function checkIsFileOfType(str, fileType) {
  return str.endsWith("." + fileType) ? str : null;
}

console.log(checkIsFileOfType("TAtrimg001a.svD", "svg"));
console.log(checkIsFileOfType("TAtrimg001a.svg", "svg"));

Upvotes: 0

CRice
CRice

Reputation: 32176

Straightforward with regex. The string .match method takes a regex and returns either:

  • null if there was no match.
  • An array otherwise, where the first element is the entire matched string, and the remaining elements are each respective capture group (if any).

So for this case, you just want the whole match, so just taking that first item should be fine. The example regex below just looks for any string of non-whitespace characters that ends with .svg. You may want to broaden or tighten that to meet your exact use case.

src = 'The expression $ a{\color{blue}{x}}^2 + b{\color{blue}{x}} + c$ is said to be quadratic when TAtrimg001a.svg is \neq 0$'

function findFileName(str, ext) {
    const match = str.match(new RegExp(`\\w+\\.${ext}`));
    return match && match[0]
}

console.log(findFileName(src, "svg"))

Minor Note: When passing a string to the RegExp constructor, backslashes must be doubled, since the first backslash escapes the second as part of the string.

Upvotes: 2

Related Questions