In below code req.body.urlOfFolder
largest string with /
, This string last segment I want to split or remove I tried with split (see below code), So how to remove last segement ?
console.log(req.body.urlOfFolder); // 131/131/980/981/982/983/984/985/986/987/988
var urloffolder = req.body.urlOfFolder.split('/')[0];
console.log(urloffolder); // 131 (this output i get)
console.log(urloffolder); // 131/131/980/981/982/983/984/985/986/987 (this output i want)
In below code req.body.urlOfFolder
largest string with /
, This string last segment I want to split or remove I tried with split (see below code), So how to remove last segement ?
console.log(req.body.urlOfFolder); // 131/131/980/981/982/983/984/985/986/987/988
var urloffolder = req.body.urlOfFolder.split('/')[0];
console.log(urloffolder); // 131 (this output i get)
console.log(urloffolder); // 131/131/980/981/982/983/984/985/986/987 (this output i want)
Share
Improve this question
asked Dec 19, 2018 at 12:04
DharmeshDharmesh
6,02318 gold badges49 silver badges67 bronze badges
4 Answers
Reset to default 4You could split by slashes, pop off the last 988
that you don't want, then join again:
const url = '131/131/980/981/982/983/984/985/986/987/988';
const splits = url.split('/');
splits.pop();
const fixedUrl = splits.join('/');
console.log(fixedUrl);
Another option would be to use a regular expression:
const url = '131/131/980/981/982/983/984/985/986/987/988';
const fixedUrl = url.match(/\d+(?:\/\d+)+(?=\/\d+$)/)[0];
console.log(fixedUrl);
One more way of doing is using substr
and lastIndexOf
let str = "131/131/980/981/982/983/984/985/986/987/988";
let op = str.substr(0,str.lastIndexOf('/'));
console.log(op);
Regex method
let str = "131/131/980/981/982/983/984/985/986/987/988";
let op = str.match(/.*(?=\/)/g)[0];
console.log(op);
Try following using Array.pop
let str = "131/131/980/981/982/983/984/985/986/987/988";
let temp = str.split("/"); // create array split by slashes
temp.pop(); // remove the last value 988 in our case
console.log(temp.join("/")); // join the values
You can use .splice(-1)
or .pop()
to remove the last element from your split array and then .join('/')
to rejoin your split string with /
:
.split('/')
gives:
['131', '131', '980', '981', '982', '983', '984', '985', '986', '987', '988']
.splice(-1)
or .pop()
turns the above array into (removes last element):
['131', '131', '980', '981', '982', '983', '984', '985', '986', '987']
.join('/')
turns the above array into a string:
"131/131/980/981/982/983/984/985/986/987"
const numbers = "131/131/980/981/982/983/984/985/986/987/988"
const numbersArray = numbers.split('/');
numbersArray.splice(-1);
const newNumbers = numbersArray.join('/');
console.log(newNumbers);
The above sequences can also be achieved using .reduce
:
const numbers = "131/131/980/981/982/983/984/985/986/987/988"
const newNumbers = numbers.split('/').reduce((acc, elem, i, arr) => i == arr.length-1 ? acc : acc+'/'+elem);
console.log(newNumbers);