2

Consider this string,

var string = "sometext/#a=some_text/#b=25/moretext";

What I would like to do is extract the values of "a" and "b" ("some_text" and 25)

So essentially what I want to do is find "#a=" and grab everything before the following /, then do the same for b. How can this be accomplished? Additionally, would I use the same expression to change the values in the string?

I got a hand doing this with PHP, but now I can't figure it out for JavaScript.

Edit

Here's the PHP version of extraction:

$string = "sometext/#a=some_text/#b=25/moretext";

$expr = '@#([a-z]+)=(.+?)/@';
$count = preg_match_all($expr, $string, $matches);

$result = array();
for ($i = 0; $i < $count; $i++) {
    $result[$matches[1][$i]] = $matches[2][$i];
}

print_r($result[b]);

(output would be "some_text")

2
  • What have you done in PHP? Maybe we can show you how to use the same approach in JS. Commented Jun 1, 2012 at 7:14
  • k edited post with it, thank you Commented Jun 1, 2012 at 7:17

4 Answers 4

3
var x = "sometext/#a=some_text/#b=25/moretext".match(/#a=(.+)\/.*#b=(.*).*\//)
var matches = [x[1], x[2]];

Live DEMO

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this is helpful but not quite what I was looking for, since the string can change at any given point I need to be able to grab it based on the variable name. Say "a" was removed from the string, I'd need a way to try and call "a" to see if it exists. Otherwise x[1] would be pulling "b" and x[2] wouldn't exist. Correct me if I'm wrong though.
@lan, Give me an examples of strings. I think is should work with any sting in this format. just play with the DEMO to see if it works with all the strings you can get. I think it should.
2

If you are looking to extract all the values and store them in a dictionary as name/value pairs, you can use this:

var regexp = /#(.*?)=(.*?)\//g;
var string = "sometext/#a=some_text/#b=25/moretext";
var match;

var result = {};

while ((match = regexp.exec(string)) != null) {
  result[match[1]] = match[2];
}

alert(JSON.stringify(result));

Comments

1

Based on the limited information (you did not specify what characters can appear between # and =), here's what I think you're looking for:

var string = "sometext/#a=some_text/#b=25/moretext",
    regex = /#([^=]+)=([^\/]+)/g,
    matches = [],
    match;
while (match = regex.exec(string)) {
    matches.push(match[2]);
}
// matches -> ["some_text", "25"]

If you want to change the values in the string, you can do this with the same regex as before:

string = string.replace(regex, "#$1=new_value");
// -> "sometext/#a=new_value/#b=new_value/moretext"

Comments

0

To change the value of string

var string = "sometext/#a=some_text/#b=25/moretext"; 

Regex.Replace(string,"(#a=).(/)",,"$1New Text$2");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.