Home > Blockchain >  Node split string by last space
Node split string by last space

Time:03-16

var str="72 tocirah abba tesh sneab";

I currently have this string and want a new string that is called "72 tocirah abba tesh". What is the best way to do this in node/Javascript?

CodePudding user response:

You can use replace, like:

"72 tocirah abba tesh sneab".replace(/\s\w $/, '')

(This replaces the last space and word with an empty string)

CodePudding user response:

I would solve it like that:

let str = "72 tocirah abba tesh sneab"

Split by " ":

let list = str.split(" ") // [72,tocirah,abba,tesh,sneab]

Remove the last element using pop():

list.pop() // [72,tocirah,abba,tesh]

Then join it back together:

str = list.join(" ") // 72 tocirah abba tesh 

CodePudding user response:

Another one-liner:

"72 tocirah abba tesh sneab".split(" ").slice(0, -1).join(" ")

CodePudding user response:

Following is one of the ways to handle this.

use lastIndexOf function

const lastSpacePosition = str.lastIndexOf(" ");
// in case there is no space in the statement. take the whole string as result.

if(lastSpacePosition < 0) {
    lastSpacePosition = str.length;
}

str.substr(0, lastSpacePosition);

There are other ways to handle this using regEx, split->join as well

  • Related