Replace strings from left until the first occuring string in Javascript - javascript

I am trying to figure out how to replace example:
sw1_code1_number1_jpg --> code1_number1_jpg
hon2_noncode_number2_jpg --> noncode_number2_jpg
ccc3_etccode_number3_jpg --> etccode_number3_jpg
ddd4_varcode_number4_jpg --> varcode_number4_jpg
So the results are all string after the first _
If it doesn't find any _ then do nothing.
I know how to find and replace strings, str.replace, indexof, lastindexof but dont know how remove up to the first found occurrence.
Thank You

Use the replace method with a regular expression:
"sw1_code1_number1_jpg".replace(/^.*?_/, "");

You could split your string and get a slice
var str = 'sw1_code1_number1_jpg';
var finalStr = str.split('_').slice(1).join('_') || str;
If your original string does not contain an underscore, then it returns the original string.
UPDATE A simpler one with slice (still works with strings not containing underscores)
var str = 'sw1_code1_number1_jpg';
var finalStr = str.slice(str.indexOf('_') + 1);
This one works in all cases because when no underscore is found, -1 is returned and as we add 1 to the index we call str.slice(0) which is equal to str.

There are several approaches you can take:
var str = 'sw1_code1_number1_jpg';
var arr = str.split('_');
arr.shift();
var newSfr = arr.join('_');
Or you could use slice or replace:
var str = 'sw1_code1_number1_jpg';
var newStr = str.slice(str.indexOf('_')+1);
Or
var newStr = 'sw1_code1_number1_jpg'.replace(/^[^_]+_/,'');

Related

Extract words with RegEx

I am new with RegEx, but it would be very useful to use it for my project. What I want to do in Javascript is this :
I have this kind of string "/this/is/an/example" and I would like to extract each word of that string, that is to say :
"/this/is/an/example" -> this, is, an, example. And then use each word.
Up to now, I did :
var str = "/this/is/a/test";
var patt1 = /\/*/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
and it returns me : /,,,,,/,,,/,,/,,,,,
I know that I will have to use .slice function next if I can identify the position of each "/" by using search for instance but using search it only returns me the index of the first "/" that is to say in this case 0.
I cannot find out.
Any Idea ?
Thanks in advance !
Use split()
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
var str = "/this/is/a/test";
var array = str.split('/');
console.log(array);
In case you want to do with regex.
var str = "/this/is/a/test";
var patt1 = /(\w+)/g;
var result = str.match(patt1)
console.log(result);
Well I guess it depends on your definition of 'word', there is a 'word character' match which might be what you want:
var patt1 = /(\w+)/g;
Here is a working example of the regex
Full JS example:
var str = "/this/is/a/test";
var patt1 = /(\w+)/g;
var match = str.match(patt1);
var output = match.join(", ");
console.log(output);
You can use this regex: /\b[^\d\W]+\b/g, to have a specific word just access the index in the array. e.g result[0] == this
var str = "/this/is/a/test";
var patt1 = /\b[^\d\W]+\b/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
<span id="demo"></span>

how can i replace first two characters of a string in javascript?

lets suppose i have string
var string = "$-20455.00"
I am trying to swap first two characters of a string. I was thinking to split it and make an array and then replacing it, but is there any other way? Also, I am not clear how can I achieve it using arrays? if I have to use arrays.
var string = "-$20455.00"
How can I achieve this?
You can use the replace function in Javascript.
var string = "$-20455.00"
string = string.replace(/^.{2}/g, 'rr');
Here is jsfiddle: https://jsfiddle.net/aoytdh7m/33/
You dont have to use arrays. Just do this
string[1] + string[0] + string.slice(2)
You can split to an array, and then reverse the first two characters and join the pieces together again
var string = "$-20455.00";
var arr = string.split('');
var result = arr.slice(0,2).reverse().concat(arr.slice(2)).join('');
document.body.innerHTML = result;
try using the "slice" method and string concatenation:
stringpart1 = '' //fill in whatever you want to replace the first two characters of the first string with here
string2 = stringpart1 + string.slice(1)
edit: I now see what you meant by "swap". I thought you meant "swap in something else". Vlad's answer is best to just switch the first and the second character.
Note that string[0] refers to the first character in the string, and string[1] to the second character, and so on, because code starts counting at 0.
var string = "$-20455.00";
// Reverse first two characters
var reverse = string.slice(0,2).split('').reverse().join('');
// Concat again with renaming string
var result= reverse.concat(string.slice(2));
document.body.innerHTML = result;
let finalStr = string[1] + string[0] + string.slice(2); //this will give you the result

get particular strings from a text that separated by underscore

I am trying to get the particular strings from the text below :
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
From this i have to get the following strings: "LAST", "BRANCH" and "JENKIN".
I used the code below to get "JENKIN";
var result = str.substr(str.lastIndexOf("_") +1);
It will get the result "JENKIN.bin". I need only "JENKIN".
Also the input string str sometimes contains this ".bin" string.
with substring() function you can extract text you need with defining start and end position. You have already found the start position with str.lastIndexOf("_") +1 and adding end position with str.indexOf(".") to substring() function will give you the result you need.
var result = str.substring(str.lastIndexOf("_") +1,str.indexOf("."));
It depends on how predictable the pattern is. How about:
var parts = str.replace(/\..+/, '').split('_');
And then parts[0] is 001AN, parts[1] is LAST, etc
You can use String.prototype.split to split a string into an array by a given separator:
var str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin';
var parts = str.split('_');
// parts is ['001AN', 'LAST', 'BRANCH', 'HYB', '1hhhhh5', 'PBTsd', 'JENKIN.bin'];
document.body.innerText = parts[1] + ", " + parts[2] + " and " + parts[6].split('.')[0];
You could do that way:
var re = /^[^_]*_([^_]*)_([^_]*)_.*_([^.]*)\..*$/;
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var matches = re.exec(str);
console.log(matches[1]); // LAST
console.log(matches[2]); // BRANCH
console.log(matches[3]); // JENKIN
This way you can reuse your RegExp anytime you want, and it can be used in other languages too.
Try using String.prototype.match() with RegExp /([A-Z])+(?=_B|_H|\.)/g to match any number of uppercase letters followed by "_B" , "_H" or "."
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var res = str.match(/([A-Z])+(?=_B|_H|\.)/g);
console.log(res)
I don't know why you want to that, but this example would be helpful.
It will be better write what exactly you want.
str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin'
find = ['LAST', 'BRANCH', 'JENKINS']
found = []
for item in find:
if item in str:
found.append(item)
print found # ['LAST', 'BRANCH']

Remove part of String in JavaScript

I have a String like
var str = "test\ntesttest\ntest\nstringtest\n..."
If I reached a configured count of lines ('\n') in the string, I want to remove the first line. That means all text to the first '\n'.
Before:
var str = "test1\ntesttest2\ntest3\nstringtest4\n...5"
After:
var str = "testtest2\ntest3\nstringtest4\n...5"
Is there a function in Javascript that I can use?
Thanks for help!
Find the first occurence of \n and return only everything after it
var newString = str.substring(str.indexOf("\n") + 1);
The + 1 means that you're also removing the new-line character so that the beginning of the new string is only text after the first \n from the original string.
You could use string.replace function also.
> var str = "test1\ntesttest2\ntest3\nstringtest4\n...5"
> str.replace(/.*\n/, '')
'testtest2\ntest3\nstringtest4\n...5'
str.substr(str.indexOf("\n")+1)
str.indexOf("\n")+1 gets the index of the first character after your first linebreak.
str.substr(str.indexOf("\n")+1) gets a substring of str starting at this index
You could write a function like this if I understand you correctly
function removePart(str, count) {
var strCount = str.split('\n').length - 1;
if(count > strCount) {
var firstIndex = str.indexOf('\n');
return str.substring(firstIndex, str.length -1);
}
return str;
}
You could use the substring(..) function. It is built-in with JavaScript. From the docs:
The substring() method extracts the characters from a string, between two specified indices, and returns the new sub string.
Usage:
mystring.substring(start,end)
The start index is required, the end index is not. If you omit the end index, it will substring from the start to the end of the string.
Or in your case, something like:
str = str.substring(str.indexOf('\n')+1);

How to use Javascript slice to extract first and last letter of a string?

How to use JavaScript slice to extract the first and last letter of a string?
Eg: "Hello World"
I need the result as "dH".
Following is my jsfiddle :
http://jsfiddle.net/vSAs8/
Here's the cleanest solution :
var output = input.slice(-1)+input[0];
If you want more slice, there's also
var output = input.slice(-1)+input.slice(0,1);
And here are alternate fun (and less efficient) solutions :
var output = input.replace(/^(.).*(.)$/,'$2$1');
or
var output = input.match(/^.|.$/g).reverse().join('');
Substr works as well:
alert(test.substr(-1,1) + test.substr(0,1));
a.charAt(a.length-1) + a.charAt(0)
var str = " Virat Kohali "
var get_string_label = function(str){
str = str.split(" ");
str = str.filter(res=>res.length>0);
str = str.map(function(res){
return res[0].toUpperCase();
});
str = str.join("");
return str;
};
console.log(get_string_label(str));
str.split(" "); method splits a String object into an array of strings by separating the string into substrings, where it will find space in string.
then str.filter(res=>res.length>0) will filter out string having zero length (for "virat kohali" string you will get empty sub-string)
after that using map function you can fetch your first letter

Categories

Resources