Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to Remove rest String from particular index value.

swechchha
Tera Contributor

Hi All,

Please let me know solution for below query.

 

var str = "xx_yy_zz_dd_tt";

I want to remove last 2 values of this sprint. how can I remove?

In my requirement one thing is common that every time I need to remove last to values.

please explain in detail and also tell how I can split that and than how can I store.

I want to store only "xx_yy_zz" part.

 

3 REPLIES 3

Mehta
Kilo Sage

@swechchha 

 

You can use var finalString =str.substr(0,str.length-2); this will always remove the last 2 letters from your string. 

 

Please mark it correct or helpful, if it resolve your query.

Manmohan K
Tera Sage

Hi @swechchha 

 

You can use slice method as shown below

 

 

var str = "xx_yy_zz_dd_tt";

var editStr = str.slice(0, -2); 

gs.print(editStr);

 

 

The slice() method is invoked on the str string and takes two parameters: 0 and -2.

  • The first parameter, 0, represents the starting index from which the extraction should begin. In this case, it is 0, which means extraction starts from the beginning of the string.
  • The second parameter, -2, represents the ending index up to which the extraction should occur. In this case, -2 means extraction will stop two characters before the end of the string.

Riya Verma
Kilo Sage

Hi @swechchha ,

 

Hope you are doing great.

 

To remove the last two values from the string "xx_yy_zz_dd_tt" and store only the "xx_yy_zz" part, you can follow these steps:

  1. Split the string into an array using the underscore (_) as the delimiter.
  2. Remove the last two elements from the array.
  3. Join the remaining elements back into a string using the underscore (_) as the separator.

Here's an example implementation in Javascript:

var str = "xx_yy_zz_dd_tt";
var parts = str.split("_"); 
parts.splice(-2); // Remove the last two elements from the array
var result = parts.join("_"); // Join the remaining elements back into a string using the underscore (_) as the separator

console.log(result); // Output: "xx_yy_zz"

 

Please mark the appropriate response as correct answer and helpful, This may help other community users to follow correct solution.
Regards,
Riya Verma