Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split or remove last character or number from string in node.js?

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)
like image 348
Dharmesh Avatar asked Apr 09 '26 18:04

Dharmesh


1 Answers

You 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);
like image 110
CertainPerformance Avatar answered Apr 11 '26 08:04

CertainPerformance