Javascript replace every 6th colon in array - javascript

I have some problems with replacing every 6th colon in my array. Have tried something with Regex, but that doesn't seem to work. I have red other questions were people are using nth and then set this variabele to the index you want to replace, but can't figure out why that isn't working. I used the join function to replace the ',' in my array with ':'.
arrayProducts[i] = arrayProducts[i].join(':');
When i use console.log(arrayProducts); this is my result:
F200:0:0.0000:1:100:0:1:KPO2:0:0.0000:1:200:0:2:HGB1:0:0.0000:1:300:0:3
This is what I want:
F200:0:0.0000:1:100:0:1,KPO2:0:0.0000:1:200:0:2,HGB1:0:0.0000:1:300:0:3
Thanks for reading!
Edit: F200, KP02 and HGB1, could also be numbers / digits like: 210, 89, 102 so the :[A-Z] method from regex doesn't work.

You can just count the number of colon occurences and replace every nth of them.
var str = 'F200:0:0.0000:1:100:0:1:KPO2:0:0.0000:1:200:0:2:HGB1:0:0.0000:1:300:0:3', counter = 0;
res = str.replace(/:/g, function(v) {
counter++;
return !(counter % 7) ? ',' : v;
});
console.log(res);

A regex solution is viable. You can use a function as the second parameter of the .replace method to make full use of backreferences.
var str = 'F200:0:0.0000:1:100:0:1:KPO2:0:0.0000:1:200:0:2:HGB1:0:0.0000:1:300:0:3';
str = str.replace(/((?:[^:]*:){6}(?:[^:]*)):/g, function() {
var matches = arguments;
return matches[1] + ',';
});
console.log(str);

What you are looking for is to split over the following expression :[A-Z]
(assuming that your rows always start with this range)
a simple solution could be:
mystring.split(/:[A-Z]/).join(',')
/:[A-Z]/ matches any : followed by a uppercase letter

You could use replace with a look for six parts with colon and replace the seventh.
var string = 'F200:0:0.0000:1:100:0:1:KPO2:0:0.0000:1:200:0:2:HGB1:0:0.0000:1:300:0:3',
result = string.replace(/(([^:]*:){6}[^:]*):/g, '$1,');
console.log(result);

Another solution (based on the number of iteration)
using map method:
str.split(':').map((v, i) => (i % 7 === 0 ? ',' : ':') + v ).join('').slice(1)
using reduce method:
str.split(':').reduce((acc,v, i) => {
return acc + (i % 7 === 0 ? ',' : ':' ) + v ;
}, '').slice(1)
Note: arrow expression does not work on old browsers

maybe you can try this approach,
loop your array and join it manually, something like :
var strarr = "F200:0:00000:1:100:0:1:KPO2:0:00000:1:200:0:2:HGB1:0:00000:1:300:0:3";
var arr = strarr.split(":")
var resStr = "";
for(var i = 0; i < arr.length; i++)
{
if(i > 0 && i%7 == 0)
resStr = resStr + "," + arr[i]
else
resStr = resStr + ( resStr == "" ? "" : ":") + arr[i];
}
console.log(resStr);

Related

Add a colon after two characters without using String.replace

I am currently using replace to insert a colon after the second character of a four-character string (1000). I think it is an elegant solution. But I wonder if there are any other elegant solutions for this? Thanks for your ideas!
Working code
const myStr = "1000";
const string = myStr.replace(/(\d{2})(\d{2})/g, '$1:$2');
console.log(string);
You could stil take a regular expression which works for any time length, like four or six digits with colon for each group of two.
const
format = s => s.replace(/.(?=(..)+$)/g, '$&:');
console.log(format('1000'));
console.log(format('100000'));
Keep it simple. Use string functions to manipulate strings:
const s1 = "1000";
const s2 = s1.slice(0, 2) + ":" + s1.slice(2);
console.log(s2);
Definitely not the best way to do that, i'm just wondering how many alternatives there are
[...'1000'].map((c, i) => i !== 0 && i % 2 === 0 ? `:${c}` : c).join('') //10:00
[...'100000'].map((c, i) => i !== 0 && i % 2 === 0 ? `:${c}` : c).join('') //10:00:00
[...'10000000'].map((c, i) => i !== 0 && i % 2 === 0 ? `:${c}` : c).join('') //10:00:00:00
You can use template literals:
const x = "1000"
const result = `${x.slice(0, 2)}:${x.slice(2)}`
console.log(result)
You can try a substring, somthing like this
var mystring = '1000';
var method1 = mystring.substring(0, 2) + ':' + mystring.substr(2);
console.log(method1);
and u can make your own function
String.prototype.insert = function(index, string) {
if (index > 0){
return this.substring(0, index) + string + this.substr(index);
}
return string + this;
};
var mystring='1000';
var method2=mystring.insert(2,':');
console.log(method2);

Replace underscore with brackets using javascript

I have a string AverageLogon_Seconds_
I need to replace the first underscore with '(' and second Underscore with ')'.
Means I need to get the text like AverageLogon(Seconds).
I have checked with str.replace(/_/g, ')'); , but it will replace both the underscore iwth ')'.
Can anyone help me on this.
Thanks
Do it with String#replace with a callback and a counter variable. Replace _ with ( in an odd position and ) in an even position where the counter variable can be used for finding out the position.
var str = 'AverageLogon_Seconds_',
i = 0;
var res = str.replace(/_/g, function() {
return i++ % 2 == 0 ? '(' : ')';
});
console.log(res);
I feel like it would be more prudent to target the "_something_" pattern as a whole. Something like
str.replace(/_([a-z0-9 -]+)_/gi, '($1)')
You can narrow that [a-z0-9 -] character class down based on the characters you expect to appear between the underscores. For now, I've got letters, numbers, spaces and hyphens.
var tests = [
'AverageLogon_Seconds_',
'AverageLogon_Seconds_ and some other_data_',
'Oh no, too_many_underscores___'],
out = document.getElementById('out'),
rx = /_([a-z0-9 -]+)_/gi;
tests.forEach(function(test) {
out.innerHTML += test + ' => ' + test.replace(rx, '($1)') + '\n';
});
<pre id="out"></pre>
Thats easy. Just a one liner needed.
testString = "AverageLogon_Seconds_";
replacedString = testString.replace(/_/, '(').replace(/_/, ')');
console.log(replacedString);
Output : "AverageLogon(Seconds)"
var str = 'AverageLogon_Seconds_', replacement = ')';
//replace the last occurence of '_' with ')'
str = str.replace(/_([^_]*)$/,replacement+'$1');
//replace the remaining '_' with '('
console.log(str);
Pranav's solution is nice. I tend to like to write things that I can very quickly reason about (i.e. sometimes less elegant). Another way (read in DJ Khaled's voice):
function replaceUnderscores(str) {
return str.split('_').map(function (part, ind) {
if (part === '') {
return '';
}
if (ind % 2 === 0) {
return part + '(';
} else {
return part + ')';
}
}).join('');
}
// "AverageLogon(Seconds)"
console.log(replaceUnderscores('AverageLogon_Seconds_'));
will this work
var t = "AverageLogon_Seconds_";
var ctr=0;
while(t.contains('_')){
if(ctr==0){
t= t.replace('_','(');
ctr++;
}
else{
t= t.replace('_',')');
ctr--;
}
}

JavaScript substr(), Get Characters in the Middle of the String

I have a string, var str = "Runner, The (1999)";
Using substr(), I need to see if ", The" is contained in str starting from 7 characters back, then if it is, remove those characters and put them in the start. Something like this:
if (str.substr(-7) === ', The') // If str has ', The' starting from 7 characters back...
{
str = 'The ' + str.substr(-7, 5); // Add 'The ' to the start of str and remove it from middle.
}
The resulting str should equal "The Runner (1999)"
Please, no regular expressions or other functions. I'm trying to learn how to use substr.
Here you go, using only substr as requested:
var str = "Runner, The (1999)";
if(str.substr(-12, 5) === ', The') {
str = 'The ' + str.substr(0, str.length - 12) + str.substr(-7);
}
alert(str);
Working JSFiddle
It should be noted that this is not the best way to achieve what you want (especially using hardcoded values like -7 – almost never as good as using things like lastIndexOf, regex, etc). But you wanted substr, so there it is.
var str = "Runner, The (1999)";
if(str.indexOf(", The") != -1) {
str = "The "+str.replace(", The","");
}
If you want to use just substr:
var a = "Runner, The (1999)"
var newStr;
if (str.substr(-7) === ', The')
newStr= 'The ' +a.substr(0,a.length-a.indexOf('The')-4) + a.substr(a.indexOf('The')+3)
Use a.substr(0,a.length-a.indexOf('The')-4) to obtain the words before "The" and a.substr(a.indexOf('The')+3) to obtain the words after it.
So, you say that the solution should be limited to only substr method.
There will be different solutions depending on what you mean by:
", The" is contained in str starting from 7 characters back
If you mean that it's found exactly in -7 position, then the code could look like this (I replaced -7 with -12, so that the code returned true):
function one() {
var a = "Runner, The (1999)";
var b = ", The";
var c = a.substr(-12, b.length);
if (c == b) {
a = "The " + a.substr(0, a.length - 12) +
a.substr(a.length - 12 + b.length);
}
}
If, however, substring ", The" can be found anywhere between position -7 and the end of the string, and you really need to use only substr, then check this out:
function two() {
var a = "Runner, The (1999)";
var b = ", The";
for (var i = a.length - 12; i < a.length - b.length; i++) {
if (a.substr(i, b.length) == b) {
a = "The " + a.substr(0, i) + a.substr(i + b.length);
break;
}
}
}

JavaScript split and join

I have a string, 15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt, I'd like to make it looks like 15.Prototypal...-Slider.txt
The length of the text is 56, how can I keep the first 12 letters and 10 last letters (incuding punctuation marks) and replace the others to ...
I don't really know how to commence the code, I made something like
var str="15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt";
str.split("// ",1);
although this gives me what I need, how do I have the results base on letters not words.
You can use str.slice().
function middleEllipsis(str, a, b) {
if (str.length > a + b)
return str.slice(0, a) + '...' + str.slice(-b);
else
return str;
}
middleEllipsis("15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt", 12, 10);
// "15.Prototypa...Slider.txt"
middleEllipsis("mpchc64.mov", 12, 10);
// "mpchc64.mov"
This function will do what you ask for:
function fixString(str) {
var LEN_PREFIX = 12;
var LEN_SUFFIX = 10;
if (str.length < LEN_PREFIX + LEN_SUFFIX) { return str; }
return str.substr(0, LEN_PREFIX) + '...' + str.substr(str.length - LEN_SUFFIX - 1);
}
You can adjust the LEN_PREFIX and LEN_SUFFIX as needed, but I've the values you specified in your post. You could also make the function more generic by making the prefix and suffix length input arguments to your function:
function fixString(str, prefixLength, suffixLength) {
if (str.length < prefixLength + suffixLength) { return str; }
return str.substr(0, prefixLength) + '...' + str.substr(str.length - suffixLength - 1);
}
I'd like to make it looks like 15.Prototypal...-Slider.txt
LIVE DEMO
No matter how long are the suffixed and prefixed texts, this will get the desired:
var str = "15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt",
sp = str.split('-'),
newStr = str;
if(sp.length>1) newStr = sp[0]+'...-'+ sp.pop() ;
alert( newStr ); //15.Prototypal...-Slider.txt
Splitting the string at - and using .pop() method to retrieve the last Array value from the splitted String.
Instead of splitting the string at some defined positions it'll also handle strings like:
11.jQuery-infinite-loop-a-Gallery.txt returning: 11.jQuery...-Gallery.txt
Here's another option. Note that this keeps the first 13 characters and last 11 because that's what you gave in your example.:
var shortenedStr = str.substr(0, 13) + '...' + str.substring(str.length - 11);
You could use the javascript substring command to find out what you want.
If you string is always 56 characters you could do something like this:
var str="15.Prototypal-Inheritance-and-Refactoring-the-Slider.txt";
var newstr = str.substring(0,11) + "..." + str.substring(45,55)
if your string varies in length I would highly recommend finding the length of the string first, and then doing the substring.
have a look at: http://www.w3schools.com/jsref/jsref_substring.asp

JavaScript: replace last occurrence of text in a string

See my code snippet below:
var list = ['one', 'two', 'three', 'four'];
var str = 'one two, one three, one four, one';
for ( var i = 0; i < list.length; i++)
{
if (str.endsWith(list[i])
{
str = str.replace(list[i], 'finish')
}
}
I want to replace the last occurrence of the word one with the word finish in the string, what I have will not work because the replace method will only replace the first occurrence of it. Does anyone know how I can amend that snippet so that it only replaces the last instance of 'one'
Well, if the string really ends with the pattern, you could do this:
str = str.replace(new RegExp(list[i] + '$'), 'finish');
You can use String#lastIndexOf to find the last occurrence of the word, and then String#substring and concatenation to build the replacement string.
n = str.lastIndexOf(list[i]);
if (n >= 0 && n + list[i].length >= str.length) {
str = str.substring(0, n) + "finish";
}
...or along those lines.
Not as elegant as the regex answers above, but easier to follow for the not-as-savvy among us:
function removeLastInstance(badtext, str) {
var charpos = str.lastIndexOf(badtext);
if (charpos<0) return str;
ptone = str.substring(0,charpos);
pttwo = str.substring(charpos+(badtext.length));
return (ptone+pttwo);
}
I realize this is likely slower and more wasteful than the regex examples, but I think it might be helpful as an illustration of how string manipulations can be done. (It can also be condensed a bit, but again, I wanted each step to be clear.)
Here's a method that only uses splitting and joining. It's a little more readable so thought it was worth sharing:
String.prototype.replaceLast = function (what, replacement) {
var pcs = this.split(what);
var lastPc = pcs.pop();
return pcs.join(what) + replacement + lastPc;
};
Thought I'd answer here since this came up first in my Google search and there's no answer (outside of Matt's creative answer :)) that generically replaces the last occurrence of a string of characters when the text to replace might not be at the end of the string.
if (!String.prototype.replaceLast) {
String.prototype.replaceLast = function(find, replace) {
var index = this.lastIndexOf(find);
if (index >= 0) {
return this.substring(0, index) + replace + this.substring(index + find.length);
}
return this.toString();
};
}
var str = 'one two, one three, one four, one';
// outputs: one two, one three, one four, finish
console.log(str.replaceLast('one', 'finish'));
// outputs: one two, one three, one four; one
console.log(str.replaceLast(',', ';'));
A simple answer without any regex would be:
str = str.substr(0, str.lastIndexOf(list[i])) + 'finish'
I did not like any of the answers above and came up with the below
function isString(variable) {
return typeof (variable) === 'string';
}
function replaceLastOccurrenceInString(input, find, replaceWith) {
if (!isString(input) || !isString(find) || !isString(replaceWith)) {
// returns input on invalid arguments
return input;
}
const lastIndex = input.lastIndexOf(find);
if (lastIndex < 0) {
return input;
}
return input.substr(0, lastIndex) + replaceWith + input.substr(lastIndex + find.length);
}
Usage:
const input = 'ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty';
const find = 'teen';
const replaceWith = 'teenhundred';
const output = replaceLastOccurrenceInString(input, find, replaceWith);
console.log(output);
// output: ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteenhundred twenty
Hope that helps!
Couldn't you just reverse the string and replace only the first occurrence of the reversed search pattern? I'm thinking . . .
var list = ['one', 'two', 'three', 'four'];
var str = 'one two, one three, one four, one';
for ( var i = 0; i < list.length; i++)
{
if (str.endsWith(list[i])
{
var reversedHaystack = str.split('').reverse().join('');
var reversedNeedle = list[i].split('').reverse().join('');
reversedHaystack = reversedHaystack.replace(reversedNeedle, 'hsinif');
str = reversedHaystack.split('').reverse().join('');
}
}
If speed is important, use this:
/**
* Replace last occurrence of a string with another string
* x - the initial string
* y - string to replace
* z - string that will replace
*/
function replaceLast(x, y, z){
var a = x.split("");
var length = y.length;
if(x.lastIndexOf(y) != -1) {
for(var i = x.lastIndexOf(y); i < x.lastIndexOf(y) + length; i++) {
if(i == x.lastIndexOf(y)) {
a[i] = z;
}
else {
delete a[i];
}
}
}
return a.join("");
}
It's faster than using RegExp.
Simple solution would be to use substring method.
Since string is ending with list element, we can use string.length and calculate end index for substring without using lastIndexOf method
str = str.substring(0, str.length - list[i].length) + "finish"
function replaceLast(text, searchValue, replaceValue) {
const lastOccurrenceIndex = text.lastIndexOf(searchValue)
return `${
text.slice(0, lastOccurrenceIndex)
}${
replaceValue
}${
text.slice(lastOccurrenceIndex + searchValue.length)
}`
}
A negative lookahead solution:
str.replace(/(one)(?!.*\1)/, 'finish')
An explanation provided by the site regex101.com,
/(one)(?!.*\1)/
1st Capturing Group (one)
one - matches the characters one literally (case sensitive)
Negative Lookahead (?!.*\1)
Assert that the Regex below does not match
. matches any character (except for line terminators)
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\1 matches the same text as most recently matched by the 1st capturing group
Old fashioned and big code but efficient as possible:
function replaceLast(origin,text){
textLenght = text.length;
originLen = origin.length
if(textLenght == 0)
return origin;
start = originLen-textLenght;
if(start < 0){
return origin;
}
if(start == 0){
return "";
}
for(i = start; i >= 0; i--){
k = 0;
while(origin[i+k] == text[k]){
k++
if(k == textLenght)
break;
}
if(k == textLenght)
break;
}
//not founded
if(k != textLenght)
return origin;
//founded and i starts on correct and i+k is the first char after
end = origin.substring(i+k,originLen);
if(i == 0)
return end;
else{
start = origin.substring(0,i)
return (start + end);
}
}
I would suggest using the replace-last npm package.
var str = 'one two, one three, one four, one';
var result = replaceLast(str, 'one', 'finish');
console.log(result);
<script src="https://unpkg.com/replace-last#latest/replaceLast.js"></script>
This works for string and regex replacements.
if (string.search(searchstring)>-1) {
stringnew=((text.split("").reverse().join("")).replace(searchstring,
subststring).split("").reverse().join(""))
}
//with var string= "sdgu()ert(dhfj ) he ) gfrt"
//var searchstring="f"
//var subststring="X"
//var stringnew=""
//results in
//string : sdgu()ert(dhfj ) he ) gfrt
//stringnew : sdgu()ert(dhfj ) he ) gXrt
str = (str + '?').replace(list[i] + '?', 'finish');

Categories