Splitting String and taking out specific elements in node js
jquery split string to array
split is not a function
I have Sample String like this
I need to take out Organisation,Guest separately. I have tried split() but can't get desired output.
var str = "Organisation/Guest/images/guestImage.jpg"; var res = str.split("/"); console.log(res); console.log(res);
Node.js, The split() function is a string function of Node. js which is used to split string into sub-strings. This function returns the output in array form. Parameters: This function accepts single parameter separator which holds the character to split the string. separator. Optional. Specifies the character, or the regular expression, to use for splitting the string. If omitted, the entire string will be returned (an array with only one item) limit. Optional. An integer that specifies the number of splits, items after the split limit will not be included in the array.
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, ''));
var yourString = "Organisation/Guest/images/guestImage.jpg"; yourString.split('/') // this returns all the words in an array yourString // returns Organisation yourString // 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 where 0 is the first index position or the first word, and so on.
- Please post the code you tried.
- Did you try
- It works for me.
- Using "Organisation/Guest/images/guestImage.jpg".split('/') I am getting [ 'Organisation', 'Guest', 'images', 'guestImage.jpg' ] in which I can easily get the elements of Array. Thanks Reyon.
- Welcome to Stack Overflow! Thank you for the code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by describing why this is a good solution to the problem, and would make it more useful to future readers with other similar questions. Please edit your answer to add some explanation, including the assumptions you've made.
- Thank you for the heads up, I'll do.