Replace a repeating character in string with a growing number [Javascript] - javascript

Replace a repeating character with a number and increment the value of number each time the character is replaced.
To explain it clearly:
I intend to add a comment to an array with its corresponding index.
Input:
[$[ , ,], $[ , ,]]
Output:
Replace $ with /**number**/:
[/**1**/[ , ,], /**2**/[ , ,]]

replace replaces the first instance by default. So you can create a function that repeatedly replaces the first appearance of '$' with '/**' + count + '**/', like so:
function replaceWithComment(str, char) {
var count = 0;
while (str.indexOf(char) > -1) {
count++;
str = str.replace(char, '/**' + count + '**/');
}
return str;
}

Related

JS regex that matches the last occurrence of a number in square brackets [duplicate]

This question already has answers here:
javascript replace last occurrence of string
(3 answers)
Using regex to replace only the last occurrence of a pattern with JS
(1 answer)
Closed 3 years ago.
In a form, I have a dynamic table where I can add or delete rows with fields in each cell. Everytime I add/delete a row, it updates the name of each <input />.
Names are like this : sheet[discounts][0][base]
And I want to change only the [0] of this string (not this exact match but a number in square brackets) .
I found the correct regex to do that :
var name = $(input).attr('name');
var str = name.replace(/\[\d+\]/, '[' + index + ']');
But I also have more complicated inputs names like this : sheet[cci][0][terms][0][commit]
And I want to change only the last occurrence of a number in square brackets :
// replace this
sheet[cci][0][terms][0][commit]
// by this
sheet[cci][0][terms][1][commit]
Use a greedy dot to consume (and match) everything up until the last [0]:
var name = 'sheet[cci][0][terms][0][commit]';
var index = 3;
var str = name.replace(/(.*)\[\d+\]/, '$1[' + index + ']');
console.log(str);
The replacement logic here is to place the [index] replacement after the first capture group which contains tth first part of the input.
Negative lookahead for a [\d+] before the end of the string:
const index = 7;
`sheet[cci][0][terms][1][commit]
sheet[cci][0][terms][2][commit]
sheet[cci][0][terms][3][commit]`.split('\n').forEach((str) => {
console.log(
str.replace(/\[\d+\](?!.*\[\d+\])/, '[' + index + ']')
)
});
If the items in square brackets that aren't pure digits (like cci, terms, and commit in your example text) always contain no digits, you can simplify it to lookahead for \D*$ (lookahead for non-digit characters, followed by the end of the string):
const index = 7;
`sheet[cci][0][terms][1][commit]
sheet[cci][0][terms][2][commit]
sheet[cci][0][terms][3][commit]`.split('\n').forEach((str) => {
console.log(
str.replace(/\[\d+\](?=\D*$)/, '[' + index + ']')
)
});

Script running into an infinite loop while trying to insert a character

I am trying to replace all the occurrences of this symbol ' (Single inverted comma) with \' (A slash and an inverted comma).
I want to ignore the first and the last inverted comma.
To put it in an another way, I am simply trying to insert a slash before the '
Sample input: 'hello's world's'
Expected output: 'hello\'s world\'s'
I have written the following code but it seems to run into an infinite loop when I execute it.
What am I doing wrong?
And is there a more efficient way of getting it done?
text = "'hello's world's'";
for(i=text.indexOf("'") ; i<text.lastIndexOf("'");i++ )
{
if(text[i]=="'")
{
text=text.substr(0,i)+ "\\" + text.substr(i);
}
}
Here i am trying to check for the charecter if it is "'" then just adding "\" infront of it .I have taken a newarray for the result.
Each time i would slice the array,intially from 0 to index of ''' and add "//" to this sliced string,next slicing index increases from previous index of"'"+1 to current index of "'" ,this continues till the length of the string
var text = "'hello's world's'";
var delimeter = "\\";
var result = "";
var newindex = 0;
for (var i = 0; i < text.length; i++) {
if (text[i] == "'") {
var str = text.slice(newindex, i);
result += "\\" + str;
newindex = i + 1;
}
}
console.log(result);
Hope it helps
Normally you can do that with replace() function:
text.replace(/'/g,"\\'");
however since you want to ignore the first and the last inverted comma, try the following code:
text = "'hello's world's'";
first = text.indexOf("'");
last = text.lastIndexOf("'");
for (i=0; i < text.length - 1; i++)
{
if (text[i] == "'" && i != first && i != last)
{
text = text.substr(0,i) + "\\" + text.substr(i);
i++;
}
}
Two problems...
First, you're starting at the index of the first quote, which you claim you want to skip. So instead of starting with:
i=text.indexOf("'")
start with:
i=text.indexOf("'") + 1
Second, and more to the point of the infinite loop, every time you add a character the last index of the last quote increases by 1. So you're forever adding slashes to the first quote and pushing the last quote further away.
So after the first loop it's:
"'hello\'s world's'"
then:
"'hello\\'s world's'"
then:
"'hello\\\'s world's'"
And so on, infinitely.
To address this, simply increment i again any time you encounter a match:
text=text.substr(0,i)+ "\\" + text.substr(i);
i++;
The idea here is that because you've modified the string, you need to further modify your placeholder in the string (i) to compensate.
Regex help a lot in this case.
text = "'hello's world's'";
newText = text.replace(/(?!^)'(.*?)(?!$)/g,"\\'");
console.log(newText);
Here's regex tester - https://regex101.com/r/9BXvYR/1
The regex excludes first and last matches of ' and includes every ' in between
And here's the plunker - https://plnkr.co/edit/eTqQ3fK9ELFyRNexGtJI?p=preview

Replace nth occurrence javascript

in this example string '1,2,3,4,5' I am trying to capture and replace the 3rd occurence of the comma , character
this code here
'1,2,3,4,5'.match(/(?:[^,]*,){2}[^,]*(,)/)
matches 1,2,3 and the comma im looking for
but not sure how to replace just the comma
'1,2,3,4,5'.replace(/(?:[^,]*,){2}[^,]*(,)/, "$")
replaces everything before 4 giving $4,5
i just want a string result like 1,2,3$4,5 for example
I have achieved this task in two different ways, with array split and slice and with a String#replace that takes a callback
//splice
let parts = [];
let str = "1,2,3,4,5";
let formatted = ((parts = str.split(",")).slice(0,3)).join("-") + ' ' + parts.slice(3).join(":")
​
//callback
let str = "1,2,3,4,5";
str.replace(/,/g, (() => {
let count = 0;
return (match, position) => {
count += 1;
if(count == 3) return ' ';
else if(count < 3) return '-';
else return ':';
});
})())
Is this even possible with a plain String#replace?
You can use capturing group and replace by first capturing group
.replace(/((?:[^,]*,){2}[^,]*),/g, "$1:");
^ ^
The captured group will capture the matched string except the third comma which is $1 in the replacement string.
console.log('1,2,3,4,5,2,3,4,5,2,3,4,5'.replace(/((?:[^,]*,){2}[^,]*),/g, "$1:"));

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 increment a string in Javascript

Let's say I have the following string:
aRandomString
I'm then checking my database to see if that string has been used before (or if there's any string that starts with the given one). If it has, I'd like to increment it. The result would be the following:
aRandomString1
If that string exists, it would become aRandomString2, and so on. I'm assuming I need to complete the following steps: 1. Check for trailing numbers or set to 0, 2. Increment those trailing numbers by 1, append that number to the original string. Just trying to figure out a solid way to accomplish this!
Update
This is what I have so far:
var incrementString = function( str ){
var regexp = /\d+$/g;
if( str.match(regexp) )
{
var trailingNumbers = str.match( regexp )[0];
var number = parseInt(trailingNumbers);
number += 1;
// Replace the trailing numbers and put back incremented
str = str.replace(/\d+$/g , '');
str += number;
}else{
str += "1";
}
return str;
}
I feel like this should be easier though.
function incrementString(str) {
// Find the trailing number or it will match the empty string
var count = str.match(/\d*$/);
// Take the substring up until where the integer was matched
// Concatenate it to the matched count incremented by 1
return str.substr(0, count.index) + (++count[0]);
};
If the match is the empty string, incrementing it will first cast the empty string to an integer, resulting the value of 0. Next it preforms the increment, resulting the value of 1.
I had to keep the leading zeros in the number, this is how I did it:
function incrementString (string) {
// Extract string's number
var number = string.match(/\d+/) === null ? 0 : string.match(/\d+/)[0];
// Store number's length
var numberLength = number.length
// Increment number by 1
number = (parseInt(number) + 1).toString();
// If there were leading 0s, add them again
while (number.length < numberLength) {
number = "0" + number;
}
return string.replace(/[0-9]/g, '').concat(number);
}

Categories

Resources