Javascript select string between 2 character - javascript

If I have a string like 1.10.6 or 1.6.5 or 1.33.10, I want to be able to select the string before the 2nd full stop.
So 1.10.6 would be 1.10, 1.6.5 would be 1.6 and 1.33.10 would be 1.33
What's the best way of doing that using javascript please?
Thanks.

Going via Array
var str = '1.10.6'.split('.').slice(0, 2).join('.');
Using a RegExp
var str = '1.10.6'.match(/\d+\.\d+/)[0];
Also
var str = '1.10.6'.split(/(\d+\.\d+)/)[1];
Using two String indexOfs
var str = '1.10.6', i = str.indexOf('.');
str = str.slice(0, str.indexOf('.', i + 1));
Using String's lastIndexOf, assuming only two .s
var str = '1.10.6', i = str.lastIndexOf('.');
str = str.slice(0, i);

var foo = '1.2.3';
var bar = foo.split('.') // '1.2.3' => ['1','2','3']
.slice(0, 2) // ['1','2','3'] => ['1','2']
.join('.'); // ['1','2'] => 1.2
Break it down in to portions first using split, select only the first 2 portions using slice (starting at the first element [element 0] and selecting 2), then rejoin it again with the periods.
String.split
Array.slice
Array.Join

if (/\.\d+\.\d+$/.test(s)){
return s.replace(/\.\d+$/, '')
}

Here is the fiddle
For example:
var newString = string.substr(0,string.lastIndexOf('.'));

Try this:
var str = str.split('.')
str = str[0]+'.'+str[1];
JSFiddle: http://jsfiddle.net/FlameTrap/hTgaZ/

Related

add hyphen after every fourth character in a string seperated by comma

I have a string as 1111111111,2222222222,333333333,....
I want to modify it as 1111-111111,2222-222222,3333-33333,....
the regex I am using is this..
var num = '1111111111,2222222222,333333333,....';
var newNum = num.toString().match(/.{4}/g).join('-');
this add hyphen after every fourth character but I am unable to reset when comma is found.
You can use the following regex:
\b\d{4}
with replacement $&-
demo
var num = '1111111111,2222222222,333333333,....';
console.log(num.replace(/\b\d{4}/g, "$&-"));
Try following
let str = '1111111111,2222222222,333333333';
let res = str.split(",").map(s => s.slice(0,4) + "-" + s.slice(4, s.length-1)).join(",");
console.log(res);
You can also use split() and substr() to get that:
var str = '1111111111,2222222222,333333333';
var res =[];
str.split(',').forEach((item)=>{
res.push(item.substr(0,4)+'-'+item.substr(4,item.length));
});
console.log(res);

JavaScript RegExp - find all prefixes up to a certain character

I have a string which is composed of terms separated by slashes ('/'), for example:
ab/c/def
I want to find all the prefixes of this string up to an occurrence of a slash or end of string, i.e. for the above example I expect to get:
ab
ab/c
ab/c/def
I've tried a regex like this: /^(.*)[\/$]/, but it returns a single match - ab/c/ with the parenthesized result ab/c, accordingly.
EDIT :
I know this can be done quite easily using split, I am looking specifically for a solution using RegExp.
NO, you can't do that with a pure regex.
Why? Because you need substrings starting at one and the same location in the string, while regex matches non-overlapping chunks of text and then advances its index to search for another match.
OK, what about capturing groups? They are only helpful if you know how many /-separated chunks you have in the input string. You could then use
var s = 'ab/c/def'; // There are exact 3 parts
console.log(/^(([^\/]+)\/[^\/]+)\/[^\/]+$/.exec(s));
// => [ "ab/c/def", "ab/c", "ab" ]
However, it is unlikely you know that many details about your input string.
You may use the following code rather than a regex:
var s = 'ab/c/def';
var chunks = s.split('/');
var res = [];
for(var i=0;i<chunks.length;i++) {
res.length > 0 ? res.push(chunks.slice(0,i).join('/')+'/'+chunks[i]) : res.push(chunks[i]);
}
console.log(res);
First, you can split the string with /. Then, iterate through the elements and build the res array.
I do not think a regular expression is what you are after. A simple split and loop over the array can give you the result.
var str = "ab/c/def";
var result = str.split("/").reduce(function(a,s,i){
var last = a[i-1] ? a[i-1] + "/" : "";
a.push(last + s);
return a;
}, []);
console.log(result);
or another way
var str = "ab/c/def",
result = [],
parts=str.split("/");
while(parts.length){
console.log(parts);
result.unshift(parts.join("/"));
parts.pop();
}
console.log(result);
Plenty of other ways to do it.
You can't do it with a RegEx in javascript but you can split parts and join them respectively together:
var array = "ab/c/def".split('/'), newArray = [], key = 0;
while (value = array[key++]) {
newArray.push(key == 1 ? value : newArray[newArray.length - 1] + "/" + value)
}
console.log(newArray);
May be like this
var str = "ab/c/def",
result = str.match(/.+?(?=\/|$)/g)
.map((e,i,a) => a[i-1] ? a[i] = a[i-1] + e : e);
console.log(result);
Couldn't you just split the string on the separator character?
var result = 'ab/c/def'.split(/\//g);

Split the date! (It's a string actually)

I want to split this kind of String :
"14:30 - 19:30" or "14:30-19:30"
inside a javascript array like ["14:30", "19:30"]
so I have my variable
var stringa = "14:30 - 19:30";
var stringes = [];
Should i do it with regular expressions? I think I need an help
You can just use str.split :
var stringa = "14:30 - 19:30";
var res = str.split("-");
If you know that the only '-' present will be the delimiter, you can start by splitting on that:
let parts = input.split('-');
If you need to get rid of whitespace surrounding that, you should trim each part:
parts = parts.map(function (it) { return it.trim(); });
To validate those parts, you can use a regex:
parts = parts.filter(function (it) { return /^\d\d:\d\d$/.test(it); });
Combined:
var input = "14:30 - 19:30";
var parts = input.split('-').map(function(it) {
return it.trim();
}).filter(function(it) {
return /^\d\d:\d\d$/.test(it);
});
document.getElementById('results').textContent = JSON.stringify(parts);
<pre id="results"></pre>
Try this :
var stringa = "14:30 - 19:30";
var stringes = stringa.split("-"); // string is "14:30-19:30" this style
or
var stringes = stringa.split(" - "); // if string is "14:30 - 19:30"; style so it includes the spaces also around '-' character.
The split function breaks the strings in sub-strings based on the location of the substring you enter inside it "-"
. the first one splits it based on location of "-" and second one includes the spaces also " - ".
*also it looks more like 24 hour clock time format than data as you mentioned in your question.
var stringa = '14:30 - 19:30';
var stringes = stringa.split("-");
.split is probably the best way to go, though you will want to prep the string first. I would go with str.replace(/\s*-\s*/g, '-').split('-'). to demonstrate:
var str = "14:30 - 19:30"
var str2 = "14:30-19:30"
console.log(str.replace(/\s*-\s*/g, '-').split('-')) //outputs ["14:30", "19:30"]
console.log(str2 .replace(/\s*-\s*/g, '-').split('-')) //outputs ["14:30", "19:30"]
Don't forget that you can pass a RegExp into str.split
'14:30 - 19:30'.split(/\s*-\s*/); // ["14:30", "19:30"]
'14:30-19:30'.split(/\s*-\s*/); // ["14:30", "19:30"]

Replace strings from left until the first occuring string in 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(/^[^_]+_/,'');

Regex remove repeated characters from a string by javascript

I have found a way to remove repeated characters from a string using regular expressions.
function RemoveDuplicates() {
var str = "aaabbbccc";
var filtered = str.replace(/[^\w\s]|(.)\1/gi, "");
alert(filtered);
}
Output: abc
this is working fine.
But if str = "aaabbbccccabbbbcccccc" then output is abcabc.
Is there any way to get only unique characters or remove all duplicates one?
Please let me know if there is any way.
A lookahead like "this, followed by something and this":
var str = "aaabbbccccabbbbcccccc";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "abc"
Note that this preserves the last occurrence of each character:
var str = "aabbccxccbbaa";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "xcba"
Without regexes, preserving order:
var str = "aabbccxccbbaa";
console.log(str.split("").filter(function(x, n, s) {
return s.indexOf(x) == n
}).join("")); // "abcx"
This is an old question, but in ES6 we can use Sets. The code looks like this:
var test = 'aaabbbcccaabbbcccaaaaaaaasa';
var result = Array.from(new Set(test)).join('');
console.log(result);

Categories

Resources