Harry
Harry

Reputation: 141

Splitting String and taking out specific elements in node js

I have Sample String like this

"Organisation/Guest/images/guestImage.jpg"

I need to take out Organisation,Guest separately. I have tried split() but can't get desired output.

Upvotes: 1

Views: 143

Answers (3)

Tamal Chowdhury
Tamal Chowdhury

Reputation: 542

var yourString = "Organisation/Guest/images/guestImage.jpg";

yourString.split('/')
// this returns all the words in an array

yourString[0] // returns Organisation
yourString[1] // returns Guest and so on

When you run .split() on a string, it will return a new array with all the words in it. In the code I am splitting by the slash /

Then I save the new array in a variable. Now you should know we can access array properties like this: array[0] where 0 is the first index position or the first word, and so on.

Upvotes: 0

Orelsanpls
Orelsanpls

Reputation: 23565

You can use of String.replace() along with regex

const regex = /Organisation\/|\/Organisation/;

console.log('Organisation/Guest/images/guestImage.jpg'.replace(regex, ''));

console.log('Guest/Organisation/images/guestImage.jpg'.replace(regex, ''));

console.log('Guest/images/guestImage.jpg/Organisation'.replace(regex, ''));

Upvotes: 1

timi-codes
timi-codes

Reputation: 21

var str = "Organisation/Guest/images/guestImage.jpg";
var res = str.split("/");
    
console.log(res[0]);
console.log(res[1]);

Upvotes: 2

Related Questions