简体   繁体   中英

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)

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); 

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); 

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM