Split string by "/" and get result in two last words JS - javascript

I have my url like https://app.asana.com/0/1154029233771298/1161783458298546; I need to get result like 1154029233771298/1161783458298546. Thanks in forward!

You can split the URL string by the / character and rejoin the last two elements by the same character:
function extractLastWords(url) {
return url.split('/').slice(-2).join('/')
}
var u = 'https://app.asana.com/0/1154029233771298/1161783458298546'
extractLastWords(u) // => "1154029233771298/1161783458298546"

var arr = str.split("/"); // create array of strings that are separated by '/'
var result = arr[arr.length-2] + "/" + arr[arr.length-1]; // concatenate last 2 indices
Or alternatively:
var result = str.split("/").slice(-2).join("/");
.split("/") - create array of strings from delimiter
.slice(-2) - get sub-array with only the last 2 elements
join("/") - concatenate all strings in array with delimiter

Related

String cutting with Javascript

I have a string like "home/back/step" new string must be like "home/back".
In other words, I have to remove the last word with '/'. Initial string always has a different length, but the format is the same "word1/word2/word3/word4/word5...."
var x = "home/back/step";
var splitted = x.split("/");
splitted.pop();
var str = splitted.join("/");
console.log(str);
Take the string and split using ("/"), then remove the last element of array and re-join with ("/")
Use substr and remove everything after the last /
let str = "home/back/step";
let result = str.substr(0, str.lastIndexOf("/"));
console.log(result);
You could use arrays to remove the last word
const text = 'home/back/step';
const removeLastWord = s =>{
let a = s.split('/');
a.pop();
return a.join('/');
}
console.log(removeLastWord(text));
Seems I got a solution
var s = "your/string/fft";
var withoutLastChunk = s.slice(0, s.lastIndexOf("/"));
console.log(withoutLastChunk)
You can turn a string in javascript into an array of values using the split() function. (pass it the value you want to split on)
var inputString = 'home/back/step'
var arrayOfValues = inputString.split('/');
Once you have an array, you can remove the final value using pop()
arrayOfValues.pop()
You can convert an array back to a string with the join function (pass it the character to place in between your values)
return arrayOfValues.join('/')
The final function would look like:
function cutString(inputString) {
var arrayOfValues = inputString.split('/')
arrayOfValues.pop()
return arrayOfValues.join('/')
}
console.log(cutString('home/back/step'))
You can split the string on the '/', remove the last element with pop() and then join again the elements with '/'.
Something like:
str.split('/');
str.pop();
str.join('/');
Where str is the variable with your text.

splitting by first occurence of comma in javascript

I have a message of the form:
var message = 'hello.there, "how are you, doing"'
Which needs to be split by the first occurrence of ',' such that I have two objects namely 'hello.there'(param 1) and "how are you, doing(param 2)" such that param 2 should be a list of arguments(length=1)and spaces should be preserved?
I have tried something like
var param2 = message.split(/,(.+)/)[1]
but that would result in param2 being a string instead of list of arguments.
Just find the first comma, then substr by that:
const pos = message.indexOf(",");
const param1 = message.substr(0, pos);
const param2 = message.substr(pos);
Or if param2 should be an array of the other strings seperated by a comma:
const [param1, ...param2] = message.split(",");
You would have to find the index of the first ,, slice the string at that index, and then split the second slice by ,:
var i = message.indexOf(','); //find the index of the first ,
var param1 = message.slice(0,i); //param1 is the slice from 0 to i
var param2 = message.slice(i+1).split(','); //param2 is the slice from i+1 splitted at ,
By the way, there are some other methods as well for splitting an array by first occurrence of a token. This SO post might interest you.

Show array as scentence except first item

How can I output an array as a scentence except the (1) item? Let's say the content of the array is: ["!report","Jay","This","is","the","reason"];
I tried this to output the items after the (1): (args.slice(1));however the output now is: "This,is,the,reason", how could I make it output as a normal scentence?
If you don't want to use built in methods, you can append each word
in the array starting at index 1 (second item).
// List of words
var words = ["!report","Jay","This","is","the","reason"];
// Empty string
var sentence = "";
// Loop through array starting at index 1 (second item)
for (let i = 1; i < words.length; i++) {
// Keep appending the words to sentence string
sentence = sentence + words[i] + " ";
}
// Print the sentence as a whole
console.log(sentence);
Or using built in functions:
// Array of strings
var array = ["!report","Jay","This","is","the","reason"];
// Cut off the first element, words is still an array though
var words = array.slice(1)
// Join each element into a string with spaces in between
var sentence = words.join(" ")
// Print as full sentence
console.log(sentence)
Output:
"Jay This is the reason"
You could slice from the second element and join the array.
console.log(["!report","Jay","This","is","the","reason"].slice(2).join(' '));
.slice() returns a new array, so when you access it as a whole, you often see a comma separated list of the array values.
But, .slice() along with .join() does the trick. .join() allows you to "join" all the array values as a single string. If you pass an argument to .join(), that argument will be used as a separator.
You can then just concatenate a period (.) to the end of the string.
console.log(["!report","Jay","This","is","the","reason"].slice(1).join(" ") + ".");
The output you desire is not very clear (do you want to remove only the first item or also the second). However the methods are the same:
you can use destructuring assignment syntax if you're es6 compliant
const arr = [a,b,...c] = ["!report","Jay","This","is","the","reason"];
let sentence = c.join(" ");
// or
let sentence2 = c.toString().replace(/,/g," ");
console.log (sentence," - ",sentence2);
or simply replace with regex and a correct pattern
const arr = ["!report","Jay","This","is","the","reason"];
let sentence = arr.toString().replace(/^[A-z! ]+?,[A-z ]+?,/,"").replace(/,/g," ");
// or
let sentence2 = arr.toString().replace(/^[A-z! ]+?,/,"").replace(/,/g," ");
console.log (sentence," - ",sentence2);
Here it is, check fiddle comments for code explanation.
var a = ["!report","Jay","This","is","the","reason"];
//removes first element from array and implodes array with spaces
var sentence = a.slice(1).join(" ");
console.log(sentence);

Javascript: String of text to array of characters

I'm trying to change a huge string into the array of chars. In other languages there is .toCharArray(). I've used split to take dots, commas an spaces from the string and make string array, but I get only separated words and don't know how to make from them a char array. or how to add another regular expression to separate word? my main goal is something else, but I need this one first. thanks
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
str = str.toLowerCase();
str = str.split(/[ ,.]+/);
You can use String#replace with regex and String#split.
arrChar = str.replace(/[', ]/g,"").split('');
Demo:
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character.";
var arrChar = str.replace(/[', ]/g,"").split('');
document.body.innerHTML = '<pre>' + JSON.stringify(arrChar, 0, 4) + '</pre>';
Add character in [] which you want to remove from string.
This will do:
var strAr = str.replace(/ /g,' ').toLowerCase().split("")
First you have to replace the , and . then you can split it:
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
var strarr = str.replace(/[\s,.]+/g, "").split("");
document.querySelector('pre').innerHTML = JSON.stringify(strarr, 0, 4)
<pre></pre>
var charArray[];
for(var i = 0; i < str.length; i++) {
charArray.push(str.charAt(i));
}
Alternatively, you can simply use:
var charArray = str.split("");
I'm trying to change a huge string into the array of chars.
This will do
str = str.toLowerCase().split("");
The split() method is used to split a string into an array of
substrings, and returns the new array.
Tip: If an empty string ("") is used as the separator, the string is
split between each character.
Note: The split() method does not change the original string.
Please read the link:
http://www.w3schools.com/jsref/jsref_split.asp
You may do it like this
var coolString,
charArray,
charArrayWithoutSpecials,
output;
coolString = "If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character.";
// does the magic, uses string as an array to slice
charArray = Array.prototype.slice.call(coolString);
// let's do this w/o specials
charArrayWithoutSpecials = Array.prototype.slice.call(coolString.replace(/[', ]/g,""))
// printing it here
output = "<b>With special chars:</b> " + JSON.stringify(charArray);
output += "<br/><br/>";
output += "<b>With special chars:</b> " + JSON.stringify(charArrayWithoutSpecials)
document.write(output);
another way would be
[].slice.call(coolString)
I guess this is what you are looking for. Ignoring all symbols and spaces and adding all characters in to an array with lower case.
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
str = str.replace(/\W/g, '').toLowerCase().split("");
alert(str);

How can I cut text from the end of a variable up until a specific character?

How can I cut text from the end of a variable up until a specific character?
Like this:
a_a_a
And I want the last "A" and split the text at the last "_":
a_a_ | a
Then I want to get 2 strings witch would be like this:
string A = a_a_
string B = a
You can use lastIndexOf to get the last occurance of the character to be searched and then substr to get the string from that index
var str = "a_a_a";
var startIndex = str.lastIndexOf("_"); //Here we are getting the last index of _ char
var result = str.substr(startIndex); //this will output `_a`
var result = str.substr(startIndex+1); //as we need only `a` we are using `startIndex + 1`
One way;
var a = s.substr(0, s.lastIndexOf("_") + 1);
var b = s.substr(a.length);

Categories