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

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

Related

JavaScript remove a character from a string and remove the previous character

How do I remove a character from a string and remove the previous character as well?
Example:
"ABCXDEXFGHXIJK"
I want to split the string by "X" and remove the previous character which returns
"ABDFGIJK" // CX, EX, HX are removed
I found this thread but it removes everything before rather than a specific amount of characters: How to remove part of a string before a ":" in javascript?
I can run a for loop but I was wondering if there was a better/simpler way to achieve this
const remove = function(str){
for(let i = 0; i < str.length; i++){
if(str[i] === "X") str = str.slice(0, i - 1) + str.slice(i + 1);
}
return str
}
console.log(remove("ABCXDEXFGHXIJK")) // ABDFGIJK
You can use String.prototype.replace and regex.
"ABCXDEXFGHXIJK".replace(/.X/g, '')
The g at the end is to replace every occurrence of .X. You can use replaceAll as well, but it has less support.
"ABCXDEXFGHXIJK".replaceAll(/.X/g, '')
If you want it to be case insensitive, use the i flag as well.
"ABCXDEXFGHXIJK".replace(/.x/gi, '')
The simplest way is to use a regular expression inside replace.
"ABCXDEXFGHXIJK".replace(/.X/g, "")
.X means "match the combination of X and any single character before it, g flag after the expression body repeats the process globally (instead of doing it once).
While not the most computationally efficient, you could use the following one-liner that may meet your definition of "a better/simpler way to achieve this":
const remove = str => str.split("X").map((ele, idx) => idx !== str.split("X").length - 1 ? ele.slice(0, ele.length - 1) : ele).join("");
console.log(remove("ABCXDEXFGHXIJK"));
Maybe you can use recursion.
function removeChar(str, char){
const index = str.indexOf(char);
if(index < 0) return str;
// removes 2 characters from string
return removeChar(str.split('').splice(index - 2, index).join());
}
Try this way (Descriptive comments are added in the below code snippet itself) :
// Input string
const str = "ABCXDEXFGHXIJK";
// split the input string based on 'X' and then remove the last item from each element by using String.slice() method.
const splittedStrArr = str.split('X').map(item => item = item.slice(0, -1));
// Output by joining the modified array elements.
console.log(splittedStr.join(''))
By using RegEx :
// Input string
const str = "ABCXDEXFGHXIJK";
// Replace the input string by matching the 'X' and one character before that with an empty string.
const modifiedStr = str.replace(/.X/g, "")
// Output
console.log(modifiedStr)

Javascript simple word counter

I am trying to make a simple word counter for a textarea element in Javascript. So far I have tried many methods but everyone fails in something. I searched the web but I only found solutions that use functions or JS commands and syntax that I still don't know. The goal is to count the words in a textarea that contains a maximum of 140 characters. The text can also be on more than one line so I have to consider the new line symbol.
Till now I wrote this:
for (let i = 0; i < text.length; i++) {
if (text[i]==' ' && (text[i-1]!==' ' && text[i-1]!=='\n')) {
wc++;
}
else if(text[i]=='\n' && text[i-1]!==' '){
wc++;
}
}
It kind of works but it counts only if after the word I press SPACE. Is there any way to start counting from when the user types just one letter?
EDIT:
I have already tried the .split(" ") method but it doesn't work with the ENTER/RETURN key. My goal is to start counting as soon as the user types a letter.
You can use split along with a regex for whitespace
let words = text.split(/\W/);
wc = words.length;
split breaks your string into an array, it creates a new entry to the array everytime it finds the expression you pass to it.
The regex /\W/ gets whitespaces (' ' and '\n')
So this way it would create an array with every word separated, and then you just need to check the length of the array
Added replace all multiple spaces with single space. Also added check if entered a new line.
document.getElementById("inputField").addEventListener("input", function(e) {
// Get the input text value
var text = this.value;
//replace all multiple spaces with single space
text = text.replace(/\s\s+/g, " ");
// Initialize the word counter
var wc = 0;
// Loop through the text
// and count spaces in it
for (let i = 0; i < text.length; i++) {
if (text[i]==' ' && (text[i-1]!==' ' && text[i-1]!=='\n')) {
wc++;
}
else if(text[i]=='\n' && text[i-1]!==' '){
wc++;
}
}
// Display it as output
document.getElementById("show").innerHTML = wc;
})
<textarea id="inputField" rows=10 cols="60">
</textarea>
<br><br>
<p> Word Count:
<span id="show">0</span>
</p>

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);

Replace a repeating character in string with a growing number [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;
}

how to retrieve a string between to same charecter

I know how to use substring() but here I have a problem, I'd like to retrieve a number between two "_" from a unknown string length. here is my string for example.
7_28_li
and I want to get the 28. How can I proceed to do so ?
Thanks.
Regex
'7_28_li'.match(/_(\d+)_/)[1]
The slashes inside match make it's contents regex.
_s are taken literally
( and ) are for retrieving the contents (the target number) later
\d is a digit character
+ is "one or more".
The [1] on the end is accesses what got matched from the first set of parens, the one or more (+) digits (\d).
Loop
var str = '7_28_li';
var state = 0; //How many underscores have gone by
var num = '';
for (var i = 0; i < str.length; i++) {
if (str[i] == '_') state++;
else if (state == 1) num += str[i];
};
num = parseInt(num);
Probably more efficient, but kind of long and ugly.
Split
'7_28_li'.split('_')[1]
Split it into an array, then get the second element.
IndexOf
var str = "7_28_li";
var num = str.substring(str.indexOf('_') + 1, str.indexOf('_', 2));
Get the start and end point. Uses the little-known second parameter of indexOf. This works better than lastIndexOf because it is guaranteed to give the first number between _s, even when there are more than 2 underscores.
First find the index of _, and then find the next position of _. Then get the substring between them.
var data = "7_28_li";
var idx = data.indexOf("_");
console.log(data.substring(idx + 1, data.indexOf("_", idx + 1)));
# 28
You can understand that better, like this
var data = "7_28_li";
var first = data.indexOf("_");
var next = data.indexOf("_", first + 1);
console.log(data.substring(first + 1, next));
# 28
Note: The second argument to indexOf is to specify where to start looking from.
Probably the easiest way to do it is to call split on your string, with your delimiter ("_" in this case) as the argument. It'll return an array with 7, 28, and li as elements, so you can select the middle one.
"7_28_li".split("_")[1]
This will work if it'll always be 3 elements. If it's more, divide the length property by 2 and floor it to get the right element.
var splitstring = "7_28_li".split("_")
console.log(splitstring[Math.floor(splitstring.length/2)]);
I'm not sure how you want to handle even length strings, but all you have to do is set up an if statement and then do whatever you want.
If you know there would be 2 underscore, you can use this
var str = "7_28_li";
var res = str.substring(str.indexOf("_") +1, str.lastIndexOf("_"));
If you want to find the string between first 2 underscores
var str = "7_28_li";
var firstIndex = str.indexOf("_");
var secondIndex = str.indexOf("_", firstIndex+1);
var res = str.substring(firstIndex+1, secondIndex);

Categories

Resources