Get second last component of a path from a string with js regex

Specified string '/root/hello/hello/world'

I want to extract the second last component into the path, that is, the second occurrence of hello.

If there is no parent, I want it to be empty. Therefore, the string /worldshould return an empty string or null.

How can I extract the last component of a path using regex or similar?

The language is javascript.

+4
source share
4 answers

You can, firstly, a splitstring on a character/ to convert it to an array:

var split = '/root/hello/hello/world'.split('/')

-> ["", "root", "hello", "hello", "world"]

Then you can grab the penultimate element:

var result = split[split.length - 2]

... but you can check the length of the array first:

var result;
if (split.length >= 2)
  result = split[split.length - 2]
+1
source

let str = '/root/hello/hello/world';

let result = str.split('/');
console.log(result[result.length-2]);
Hide result
+1

, .

const string = '/root/hello/hello/world';

// Split by the '/' character
const stringSplit = string.split('/');

// Slice the array, taking only the last 2 items.
// Then select the first one in the array
const myVal = stringSplit.slice(-2)[0];

// OR, using length
const myValLen = stringSplit[stringSplit.length - 2];

// OR, in one
const myValShort = string.split('/').slice(-2)[0];
0

Using regex, on request, you can do this with

([^/\n]*)\/[^/\n]*$

This captures the second to the last part in capture group 1.

The part ([^/\n]*)captures (inside parentheses) a fragment of characters that is not /, but not a new line ( \n). \/ensures that it is followed /and [^/\n]*$verifies that the string finally terminates with another stretch without /(or LF).

var pathArray = [
      '/root/hello/cruel/world',
      '/root/hello/world',
      '/root/world',
      '/world'
    ],
    re = /([^/\n]*)\/[^/\n]*$/;
    
pathArray.forEach(function (path) {
  document.write( '"' + path + '" returns "' + re.exec(path)[1] + '"<br/>' );
});
Run codeHide result

Try and experiment with it here in regex101 .

0
source

Source: https://habr.com/ru/post/1688580/


All Articles