FiringBlanks
FiringBlanks

Reputation: 2084

Regex - Split up URL path and place into variables

I'm really bad at regular expressions. I have a url like /this%20is%20part%20one/and%20part%20two and I need to:

1) Replace all the %20's with spaces so it's a normal looking string

2) Store each part away into it's own variable

In the end, var1 should have this is part one and var2 should have and part two

I made a picture for you:

enter image description here

Upvotes: 1

Views: 397

Answers (3)

Dineth Cooray
Dineth Cooray

Reputation: 192

Using Javascript

var re =/%20/g;
var testString = '/this%20is%20part%20one/and%20part%20two';
var splitString= testString.replace(re,' ').split('/')
var var1= splitString[1];
var var2= splitString[2];
console.log('var1:',capitalizeFirstLetters(var1));
console.log('var2:',capitalizeFirstLetters(var2));

function capitalizeFirstLetters(str){
  return str.toLowerCase().replace(/^\w|\s\w/g, function (letter) {
      return letter.toUpperCase();
  })
}

Upvotes: 3

builder-7000
builder-7000

Reputation: 7627

With sed you can do:

url="/this%20is%20part%20one/and%20part%20two"
var1=$(sed 's/%20/ /g' <<< $url | cut -d'/' -f2)
var2=$(sed 's/%20/ /g' <<< $url | cut -d'/' -f3)

Output:

>echo $va1
this is part one
>echo $var2
and part two

Upvotes: 1

Xhynk
Xhynk

Reputation: 13870

Do you really need a regex for this? Seem like using a hammer to hit a fly. You should be able to:

  1. Do a global .replace() for %20 to ' '.
  2. Explode that string with / as a delimiter.

For example:

let url  = '/this%20is%20part%20one/and%20part%20two';

url = url.replace( /%20/g, ' ', url ); //url = "/this is part one/and part two"
url = url.split('/'); //url = ["", "this is part one", "and part two"]

This will let you use array indices: url[1] and url[2] (url[0] is blank from the first / that was captured). If you don't want to use an indexed array however, suited to your example:

var1 = var2 = '';

for( i = 0, n = 1; i < url.length; ++i ){
    if( url[i].length > 0 ){
        window['var' + n++] = url[i];
    }
}

console.log(
    var1, // "this is part one"
    var2  // "and part two"
);

Upvotes: 0

Related Questions