Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract a specific word from string in Javascript

Tags:

javascript

#anotherdata=value#iamlookingforthis=226885#id=101&start=1

Given the string above how could I extract "iamlookingforthis=226885" in the string? value of it might change as this is dynamic. So, other instance might be "iamlookingforthis=1105". The location/sequence might also change, it could be in the middle or last part.

Thank you in advance.

like image 286
Jkizmo Avatar asked Oct 17 '25 02:10

Jkizmo


2 Answers

You can use Regex to match a specific text.

Like this for example

var str = '#anotherdata=value#iamlookingforthis=226885#id=101&start=1';
var value = str.match(/#iamlookingforthis=(\d+)/i)[1];

alert(value); // 226885

Explanation from Regex101:

#iamlookingforthis= matches the characters #iamlookingforthis= literally (case insensitive)

  • 1st Capturing Group (\d+)
    • \d+ matches a digit (equal to [0-9])
    • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
  • Global pattern flags
    • i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])

See

  • RegExp on MDN
  • Regex 101 - try regex and see the explanation of it and results

Another alternative would be to split the string. You could split it by #|?|&.

var str = '#anotherdata=value#iamlookingforthis=226885#id=101&start=1';
var parts = str.split(/[#\?&]/g); // split the string with these characters

// find the piece with the key `iamlookingforthis`
var filteredParts = parts.filter(function (part) {
  return part.split('=')[0] === 'iamlookingforthis';
});

// from the filtered array, get the first [0]
// split the value and key, and grab the value [1]
var iamlookingforthis = filteredParts[0].split('=')[1];

alert(iamlookingforthis); // 226885
like image 72
BrunoLM Avatar answered Oct 18 '25 16:10

BrunoLM


Here's a snippet:

var str = '#anotherdata=value#iamlookingforthis=226885#id=101&start=1';

var extracted = str.split("#").find(function(v){ 
  return v.indexOf("iamlookingforthis") > -1;
});

alert(extracted); // iamlookingforthis=226885
like image 20
Daniel Iancu Avatar answered Oct 18 '25 15:10

Daniel Iancu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!