Getting string after the first _ - javascript

I have a String such as ABC_DEF_GHI.
Using JavaScript I need to get everything after the first _ (that is, DEF_GHI in this case). There could be any number of _ in the String.
If I do something like
var str = "ABC_DEF_GHI_JKL";
var n = str.lastIndexOf('_');
var output = str.substring(n + 1);
This would give me everything after the last underscore. However, I need everything after the first underscore. Couldn't find a method such as firstIndexOf which would give me everything after the first _

You should replace your lastIndexOf() by indexOf() which will take the first occurrence
var str = "ABC_DEF_GHI_JKL";
var n = str.indexOf('_');
var output = str.substring(n + 1);
console.log(output);

var str = "ABC_DEF_GHI",
pos = str.indexOf("_");
result = str.slice(pos+1);
console.log(result);

console.log("ABC_DEF_GHI_JKL".split('_').slice(1).join('_'));
The above simply split's your string into an array, splitting at the _, and then drops the first array element, and then joins them back together with _.

One way of doing this is
var str = "ABC_DEF_GHI",
pos = str.indexOf("_");
result = str.slice(pos+1);
console.log(result);

Related

How to String include after character in nodejs, JavaScript

I want to do this in node.js
example.js
var str = "a#universe.dev";
var n = str.includes("b#universe.dev");
console.log(n);
but with restriction, so it can search for that string only after the character in this example # so if the new search string would be c#universe.dev it would still find it as the same string and outputs true because it's same "domain" and what's before the character in this example everything before # would be ignored.
Hope someone can help, please
Look into String.prototype.endsWith: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
First, you need to get the end of the first string.
var ending = "#" + str.split("#").reverse()[0];
I split your string by the # character, so that something like "abc#def#ghi" becomes the array ["abc", "def", "ghi"]. I get the last match by reversing the array and grabbing the first element, but there are multiple ways of doing this. I add the separator character back to the beginning.
Then, check whether your new string ends the same:
var n = str.endsWith(ending);
console.log(n);
var str = "a#universe.dev";
var str2 = 'c#universe.dev';
str = str.split('#');
str2 = str2.split('#');
console.log(str[1] ===str2[1]);
With split you can split string based on the # character. and then check for the element on position 1, which will always be the string after #.
Declare the function
function stringIncludeAfterCharacter(s1, s2, c) {
return s1.substr(s1.indexOf(c)) === s2.substr(s2.indexOf(c));
}
then use it
console.log(stringIncludeAfterCharacter('a#universe.dev', 'b#universe.dev', '#' ));
var str = "a#universe.dev";
var n = str.includes(str.split('#')[1]);
console.log(n);
Another way !
var str = "a#universe.dev";
var n = str.indexOf(("b#universe.dev").split('#')[1]) > -1;
console.log(n);

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.

How can I loop through string and replace all periods except the last one?

Let's say I have a string like this:
var test = my.long.file.name.zip
I am getting the total number of periods in this string with javascript like so:
var dots = (test.match(/\./g) || []).length;
I would then like to replace all of the periods in the string with underscores if there is more than one period in the string.
if(dots>"1"){
var newname = test.replace(/\./g, "_");
console.log(newname);
}
The problem is that this is replacing all of the periods. I would like to keep the last on intact. So what I would like the newname variable to read as would be:
my_long_file_name.zip
My guess is that I should use $.each() somehow to iterate over all except the last one to change the name. How should I do this?
You dont necessarily need a loop, you could do it with a more complex regex, which uses a positive lookahead
The regex /\.(?=.*\.)/g finds periods, but only where there is a subsequent period somewhere further along, which means the last one is not matched.
window.onload = function(){
var input = "my.long.file.name.zip"
var result = input.replace(/\.(?=.*\.)/g,'_')
alert(result);
}
Consider splitting the string on '.', then re-joining all but the last with '_':
var test = "my.long.file.name.zip";
parts = test.split('.');
var plen = parts.length;
if (plen > 1) {
test = parts.slice(0, plen - 1).join('_') +
"." +
parts[plen - 1];
}
console.log(test);
a lookahead group in regex will work:
var test = 'my.long.file.name.zip';
var result = test.replace(/\.(?=[^.]*\.)/g, '_');
alert(result);
this matches a dot followed by ('anything but dot' and another dot), replacing only what is outside the group
var test = 'my.long.file.name.zip';
var last_index = test.lastIndexOf('.');
var newname = test;
if (-1 !== last_index) {
newname = test.replace(/\./g, '_');
newname = newname.substring(0, last_index).concat('.', newname.substring(last_index + 1));
}
console.log(newname);

Incrementing a number in a string

I have the following string: 0-3-terms and I need to increment the 3 by 20 every time I click a button, also the start value might not always be 3 but I'll use it in this example..
I managed to do this using substring but it was so messy, I'd rather see if it's possible using Regex but I'm not good with Regex. So far I got here, I thought I would use the two hyphens to find the number I need to increment.
var str = '0-3-terms';
var patt = /0-[0-9]+-/;
var match = str.match(patt)[0];
//output ["0-3-"]
How can I increment the number 3 by 20 and insert it back in to the str, so I get:
0-23-terms, 0-43-terms, 0-63-terms etc.
You're doing a replacement. So use .replace.
var str = '0-3-terms';
var patt = /-(\d+)-/;
var result = str.replace(patt,function(_,n) {return "-"+(+n+20)+"-";});
Another option is to use .split instead of regex, if you prefer. That would look like this:
var str = '0-3-terms';
var split = str.split('-');
split[1] = +split[1] + 20;
var result = split.join('-');
alert(result);
I don't understand why you are using regex. Simply store the value and create string when the button is called..
//first value
var value = 3;
var str = '0-3-terms';
//after clicking the button
value = value+20;
str = "0-" + value + "-terms"

javascript get characters between slashes

Can someone please help. I need to get the characters between two slashes e.g:
Car/Saloon/827365/1728374
I need to get the characters between the second and third slashes. i.e 827365
You can use the split() method of the String prototype, passing in the slash as the separator string:
const value = 'Car/Saloon/827365/1728374';
const parts = value.split('/');
// parts is now a string array, containing:
// [ "Car", "Saloon", "827365", "1728374" ]
// So you can get the requested part like this:
const interestingPart = parts[2];
It's also possible to achieve this as a one-liner:
const interestingPart = value.split('/')[2];
Documentation is here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
This will simply alert 1728374, as you want
alert("Car/Saloon/827365/1728374".split('/')[3]);
or, a bit longer, but also more readable:
var str = "Car/Saloon/827365/1728374";
var exploded = str.split('/');
/**
* str[0] is Car
* str[1] is Saloon
* str[2] is 827365
* str[3] is 1728374
*/
Try the_string.split('/') - it gives you an array containing the substrings between the slashes.
try this:
var str = 'Car/Saloon/827365/1728374';
var arr = str.split('/'); // returns array, iterate through it to get the required element
Use split to divide the string in four parts:
'Car/Saloon/827365/1728374'.split('/')[2]
Gives "827365"
You will have to use the .split() function like this:
("Car/Saloon/827365/1728374").split("/")[2];
"Car/Saloon/827365/1728374".split("/")[2]
"Car/Saloon/827365/1728374".split("/")[3]
How many you want you take it.. :)
var str = "Car/Saloon/827365/1728374";
var items = str.split("/");
for (var i = 0; i < items.length; i++)
{
alert(items[i]);
}
OR
var lastItem = items[items.length - 1]; // yeilds 1728374
OR
var lastItem1728374 = items[2];

Categories