This question already has answers here:
Remove a character at a certain position in a string - javascript [duplicate]
(8 answers)
Closed 5 years ago.
I am having problem finding the proper method to accomplish this in JS. I want to iterate through each character of string (assume all lower cased) while removing ith character only.
So if I have string abc, I will iterate it three times and it will print:
'bc' //0th element is removed
'ac' //1st element is removed
'ab' //2nd element is removed
I thought I could do it with replace, but it did not work on string having multiple same characters.
Something like this:
str = 'batman';
for(var i = 0; i < str.length; i++){
var minusOneStr = str.replace(str[i], '');
console.log(minusOneStr);
}
"atman"
"btman"
"baman"
"batan"
"btman" //need it to be batmn
"batma"
I realized this didn't work because str.replace(str[i], ''); when str[i] is a, it will replace the first instance of a. It will never replace the second a in batman. I checked on substring, splice, slice method, but none suits mf purpose.
How can I accomplish this?
Instead of using .replace() you'd just concatenate slices of the string before and after the current index.
var str = 'batman';
for (var i = 0; i < str.length; i++) {
var minusOneStr = str.slice(0, i) + str.slice(i + 1);
console.log(minusOneStr);
}
This is because, as you noted, .replace(), when given a string, always replace the first instance found.
Related
This question already has answers here:
How to parse CSV data?
(14 answers)
Closed 6 months ago.
If given an comma separated string as follows
'UserName,Email,[a,b,c]'
i want a split array of all the outermost elements so expected result
['UserName','Email', '[a,b,c]']
string.split(',') will split across every comma but that wont work so any suggestions? this is breaking a CSV reader i have.
I wrote 2 similar answers, so might as well make it a 3rd instead of referring you there. It's a stateful split. This doesn't support nested arrays, but can easily made so.
var str = 'UserName,Email,[a,b,c]'
function tokenize(str) {
var state = "normal";
var tokens = [];
var current = "";
for (var i = 0; i < str.length; i++) {
c = str[i];
if (state == "normal") {
if (c == ',') {
if (current) {
tokens.push(current);
current = "";
}
continue;
}
if (c == '[') {
state = "quotes";
current = "";
continue;
}
current += c;
}
if (state == "quotes") {
if (c == ']') {
state = "normal";
tokens.push(current);
current = "";
continue;
}
current += c;
}
}
if (current) {
tokens.push(current);
current = "";
}
return tokens;
}
console.log(tokenize(str))
You can do this by matching the string to this Regex:
/(^|(?<=,))\[[^[]+\]|[^,]+((?=,)|$)/
let string = '[a,b,c],UserName,[1,2],Email,[a,b,c],password'
let regex = /(^|(?<=,))\[[^[]+\]|[^,]+((?=,)|$)/g
let output = string.match(regex);
console.log(output)
The regex can be summarized as:
Match either an array or a string that's enclosed by commas or at the start/end of our input
The key token we're using is alternative | which works as a sort of either this, or that and since the regex engine is eager, when it matches one, it moves on. So if we match and array, then we move on and don't consider what's inside.
We can break it down to 3 main sections:
(^|(?<=,))
^ Match from the beginning of our string
| Alternatively
(?<=,) Match a string that's preceded by a comma without returning the comma. Read more about positive lookaround here.
\[[^[]+\] | [^,]+
\[[^[]+\] Match a string that starts with [ and ends with ] and can contain a string of one or more characters that aren't [
This because in [1,2],[a,b] it can match the whole string at once since it starts with [ and ends with ]. This way our condition stops that by removing matches that also contain [ indicating that it belongs the second array.
| Alternatively
[^,]+ Match a string of any length that doesn't contain a comma, for the same reason as the brackets above since with ,asd,qwe, technically all of asd,qwe is enclosed with commas.
((?=,)|$)
(?=,) Match any string that's followed by a comma
| Alternatively
$ Match a string that ends with the end of the main string. Read here for a better explanation.
This question already has answers here:
Find and replace nth occurrence of [bracketed] expression in string
(4 answers)
Closed 5 years ago.
This question been asked before, but I did not succeed in solving the problem.
I have a string that contains numbers, e.g.
var stringWithNumbers = "bla_3_bla_14_bla_5";
I want to replace the nth occurence of a number (e.g. the 2nd) with javascript. I did not get farer than
var regex = new RegExp("([0-9]+)");
var replacement = "xy";
var changedString = stringWithNumbers.replace(regex, replacement);
This only changes the first number.
It was suggested to use back references like $1, but this did not help me.
The result should, for example, be
"bla_3_bla_xy_bla_5" //changed 2nd occurence
You may define a regex that matches all occurrences and pass a callback method as the second argument to the replace method and add some custom logic there:
var mystr = 'bla_3_bla_14_bla_5';
function replaceOccurrence(string, regex, n, replace) {
var i = 0;
return string.replace(regex, function(match) {
i+=1;
if(i===n) return replace;
return match;
});
}
console.log(
replaceOccurrence(mystr, /\d+/g, 2, 'NUM')
)
Here, replaceOccurrence(mystr, /\d+/g, 2, 'NUM') takes mystr, searches for all digit sequences with /\d+/g and when it comes to the second occurrence, it replaces with a NUM substring.
var stringWithNumbers = "bla_3_bla_14_bla_5";
var n = 1;
var changedString = stringWithNumbers.replace(/[0-9]+/g,v => n++ == 2 ? "xy" : v);
console.log(changedString);
This question already has answers here:
Strip HTML from Text JavaScript
(44 answers)
removing html tags from string
(3 answers)
Closed 7 years ago.
I need to get rid of any text inside < and >, including the two delimiters themselves.
So for example, from string
<brev-y>th</brev-y><sw-ex>a</sw-ex><sl>t</sl>
I would like to get this one
that
This is what i've tried so far:
var str = annotation.split(' ');
str.substring(str.lastIndexOf("<") + 1, str.lastIndexOf(">"))
But it doesn't work for every < and >.
I'd rather not use RegEx if possible, but I'm happy to hear if it's the only option.
You can simply use the replace method with /<[^>]*>/g.It matches < followed by [^>]* any amount of non> until > globally.
var str = '<brev-y>th</brev-y><sw-ex>a</sw-ex><sl>t</sl>';
str = str.replace(/<[^>]*>/g, "");
alert(str);
For string removal you can use RegExp, it is ok.
"<brev-y>th</brev-y><sw-ex>a</sw-ex><sl>t</sl>".replace(/<\/?[^>]+>/g, "")
Since the text you want is always after a > character, you could split it at that point, and then the first character in each String of the array would be the character you need. For example:
String[] strings = stringName.split("<");
String word = "";
for(int i = 0; i < strings.length; i++) {
word += strings[i].charAt(0);
}
This is probably glitchy right now, but I think this would work. You don't need to actually remove the text between the "<>"- just get the character right after a '>'
Using a regular expression is not the only option, but it's a pretty good option.
You can easily parse the string to remove the tags, for example by using a state machine where the < and > characters turns on and off a state of ignoring characters. There are other methods of course, some shorter, some more efficient, but they will all be a few lines of code, while a regular expression solution is just a single replace.
Example:
function removeHtml1(str) {
return str.replace(/<[^>]*>/g, '');
}
function removeHtml2(str) {
var result = '';
var ignore = false;
for (var i = 0; i < str.length; i++) {
var c = str.charAt(i);
switch (c) {
case '<': ignore = true; break;
case '>': ignore = false; break;
default: if (!ignore) result += c;
}
}
return result;
}
var s = "<brev-y>th</brev-y><sw-ex>a</sw-ex><sl>t</sl>";
console.log(removeHtml1(s));
console.log(removeHtml2(s));
There are several ways to do this. Some are better than others. I haven't done one lately for these two specific characters, so I took a minute and wrote some code that may work. I will describe how it works. Create a function with a loop that copies an incoming string, character by character, to an outgoing string. Make the function a string type so it will return your modified string. Create the loop to scan from incoming from string[0] and while less than string.length(). Within the loop, add an if statement. When the if statement sees a "<" character in the incoming string it stops copying, but continues to look at every character in the incoming string until it sees the ">" character. When the ">" is found, it starts copying again. It's that simple.
The following code may need some refinement, but it should get you started on the method described above. It's not the fastest and not the most elegant but the basic idea is there. This did compile, and it ran correctly, here, with no errors. In my test program it produced the correct output. However, you may need to test it further in the context of your program.
string filter_on_brackets(string str1)
{
string str2 = "";
int copy_flag = 1;
for (size_t i = 0 ; i < str1.length();i++)
{
if(str1[i] == '<')
{
copy_flag = 0;
}
if(str1[i] == '>')
{
copy_flag = 2;
}
if(copy_flag == 1)
{
str2 += str1[i];
}
if(copy_flag == 2)
{
copy_flag = 1;
}
}
return str2;
}
I am trying to construct a statement (because the client requests for it) and want to remove the last statement in a for loop but still included in between the loop.
This is what I am trying to achieve (as a broad example as I can):
I selected: 2 years period, 2 yrs period, 1 years period, 1 yrs period.
I managed to achieve this but at the very end, it doesn't end with a period, it ended with a comma instead.
The number of years is selected by the user, therefore I declared a variable.
Here is my code in Javascript:
var out_content = document.getElementById("content");
var in_year = 2;
var in_period = ["years","yrs"];
var sText = "I selected: ";
for (var i=0;i<in_year; in_year--)
{
for (var p=0;p<in_period.length;p++)
{
sText += in_year + in_period[p];
sText += ",";
}
}
out_content.innerHTML = sText;
What do I do?
The simplest way to solve your problem is to just remove the last character (the unwanted comma) and put a period there instead.
sText.slice(0,-1)+'.'
Slicing from 0 to -1 means getting the characters from the beginning to the one before the last.
Add the if statement before comma and check with the variable value with p and the condition should pass but should fail on last loop statement
Removing the last character from your string, when predictable, can be easily achieved as such:
sText = sText.substring(0, sText.length-2);
Substring takes two parameters, start (0) and end (you want length minus 1 here, but since its viewed as an array you might want length - 2). Heres more info: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/substring
A better way to handle this kind of problem is to use an array, then join array elements:
var sText = "I selected: ";
var aText = [];
for (var i=0;i<in_year; in_year--)
{
for (var p=0;p<in_period.length;p++)
{
aText.push(in_year + in_period[p]);
}
}
sText += aText.join() + '.';
This question already has answers here:
detect differences between two strings with Javascript
(2 answers)
Closed 8 years ago.
I am wondering if there is a way in JavaScript by which I can detect which part of my Strings makes them different from each other.
Let's say I have three strings as follows:
String1 = "Java1String"
String2 = "Java2String"
String3 = "Java3String"
If I choose my first String as a main one, the part which makes it different from the others is 1.
Is there any way using either JavaScript or jQuery by which I can find this part?
var String1 = "Java1String",
String2 = "Java2String",
String3 = "Java3String";
var j = 0;
for(var i = 0; i < String1.length; i++){
if(String1.charAt(i) != String2.charAt(j))
alert(String1.charAt(i) +" != "+ String2.charAt(j));
j++;
}
You can check out a demo of this code with this jsfiddle.
You can compare two strings like this. This will give you the characters which are different.
var String1 = "Java1String",
String2 = "Java2String",
String3 = "Java3String";
var j = 0;
for(var i = 0; i < String1.length; i++){
if(String1.charAt(i) != String2.charAt(j))
alert(String1.charAt(i) +" != "+ String2.charAt(j));
j++;
}
You can check out Demo of this code on this link
http://jsfiddle.net/enL9b3jv/1/
The naive solution would be to convert each string into an array and iterate over the arrays, compare the character at each index until you find an index that doesn't match, and then write that index to a variable. Below is a Jsbin that does just that, but just as DevIshOne states, there are many questions to answer here...
http://jsbin.com/dugovemoxupu/1/edit