Find string in array and remove - javascript

I want to find a string in an array sql and remove the string. The string would be like:
" specimen.snop_code = ''"
There will be 4 digits between the single qoutes, which could be anything. I was thinking of using regex to find the string.
Tried just using pop() but I need to target the string to be removed from the array. Note that I need to remove all instances of the string. So something like:
disease_filter = new RegExp(" specimen.snop_code = ''", 'g');
for (var i=sql.length-1; i>=0; i--) {
if (sql[i] === disease_filter) {
array.splice(i, 1);
}
}
So how can I make " specimen.snop_code = '*'" into a regular expression with a wildcard as shown between the single quotes?

You can use .replace with a regex as the first parameter:
var input = " specimen.snop_code = 'something'";
var disease_filter = input.replace(/'(.*)'/gi, "'other stuff'");
// disease_filter is now "specimen.snop_code = 'other stuff'"
edit: removed unneccesary escaping as commented.

Related

Search in string and quote around occurrence

Working with Javascript I need to be able to search a string input from a user and replace occurrences of semicolons with commas. Issue I have ran into is I need to be able to search the string for any commas that already exist, and quote around to the last and next occurrence of the semicolon.
Example:
User input is 12345;Joran,Michael;02;17;63 it should be converted to 12345,"Joran,Michael",02,17,63
My includes is able to locate the occurrence of a comma in the original string var srch = source.includes(","); and my replace is var converted = source.replace(/;/g, ","); which works fine, just need to figure out how to get to the last/next semicolon to place the quotes.
Using an if/else depending on if srch evaluates to True -- if true, add the quotes and then convert the rest of the string and return to the user; if false, convert and return.
I'm sure there's a way to do this with regex that just hasn't came to me yet so any suggestions on what to look at would be great.
I'd do this in two steps. First match non-; characters which have at least one ,, and surround them with quotes. Then replace all ;s in the result with ,:
console.log(
'12345;Joran,Michael;02;17;63'
.replace(/[^;,]*,[^;]*/g, '"$&"')
.replace(/;/g, ',')
);
Split the string by ;
.split(';')
which gives you an array.
Convert the elements that include a ',' to "${element}"
.map(s => s.includes(',') ? `"${s}"` : s )
Convert the array back to string
.join(',')
var str = '12345;Joran,Michael;02;17;63';
var arr = str.split(";");
var letters = /^[A-Za-z]/;
var final_str = "";
for (var i = 0; i < arr.length; i++) {
final_str = arr[i].match(letters)?final_str +'"'+ arr[i]+'"'+",":final_str + arr[i]+",";
}
console.log(final_str.substring(0,final_str.length -1));

Javascript: String of text to array of characters

I'm trying to change a huge string into the array of chars. In other languages there is .toCharArray(). I've used split to take dots, commas an spaces from the string and make string array, but I get only separated words and don't know how to make from them a char array. or how to add another regular expression to separate word? my main goal is something else, but I need this one first. thanks
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
str = str.toLowerCase();
str = str.split(/[ ,.]+/);
You can use String#replace with regex and String#split.
arrChar = str.replace(/[', ]/g,"").split('');
Demo:
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character.";
var arrChar = str.replace(/[', ]/g,"").split('');
document.body.innerHTML = '<pre>' + JSON.stringify(arrChar, 0, 4) + '</pre>';
Add character in [] which you want to remove from string.
This will do:
var strAr = str.replace(/ /g,' ').toLowerCase().split("")
First you have to replace the , and . then you can split it:
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
var strarr = str.replace(/[\s,.]+/g, "").split("");
document.querySelector('pre').innerHTML = JSON.stringify(strarr, 0, 4)
<pre></pre>
var charArray[];
for(var i = 0; i < str.length; i++) {
charArray.push(str.charAt(i));
}
Alternatively, you can simply use:
var charArray = str.split("");
I'm trying to change a huge string into the array of chars.
This will do
str = str.toLowerCase().split("");
The split() method is used to split a string into an array of
substrings, and returns the new array.
Tip: If an empty string ("") is used as the separator, the string is
split between each character.
Note: The split() method does not change the original string.
Please read the link:
http://www.w3schools.com/jsref/jsref_split.asp
You may do it like this
var coolString,
charArray,
charArrayWithoutSpecials,
output;
coolString = "If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character.";
// does the magic, uses string as an array to slice
charArray = Array.prototype.slice.call(coolString);
// let's do this w/o specials
charArrayWithoutSpecials = Array.prototype.slice.call(coolString.replace(/[', ]/g,""))
// printing it here
output = "<b>With special chars:</b> " + JSON.stringify(charArray);
output += "<br/><br/>";
output += "<b>With special chars:</b> " + JSON.stringify(charArrayWithoutSpecials)
document.write(output);
another way would be
[].slice.call(coolString)
I guess this is what you are looking for. Ignoring all symbols and spaces and adding all characters in to an array with lower case.
var str = " If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character."
str = str.replace(/\W/g, '').toLowerCase().split("");
alert(str);

Capturing String Segments between Special Characters using Regular Expressions

I have the following string of text:
textString1:textString2:textString3:textString4
I'm looking to capture each text string and assign them to variables.
I've somehow managed to come up with the following:
var errorText = 'AAAA:BBBB:CCCC:DDDD';
var subString, intro, host, priority, queue = '';
var re = /(.+?\:)/g;
subString = errorText.match(re);
intro = subString[0];
host = subString[1];
priority = subString[2];
//queue = subString[3];
console.log(intro + " " + host + " " + priority);
JS Bin Link
However, I'm having problems with:
capturing the last group, since there is no : at the end
the variables contain : which I'd like to strip
You don't need a regex for this - just use errorText.split(':') to split by a colon. It will return an array.
And if you then want to add them together with spaces, you could do a simple replace instead: errorText.replace(/:/g,' ').
use split method for this.it will return array of string then iterate through array to get string:
var errorText = 'AAAA:BBBB:CCCC:DDDD';
var strArr=errorText.split(':');
console.log(errorText.split(':'));
for(key in strArr){
console.log(strArr[key]);
}

jQuery multiple replace [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 8 years ago.
I'm trying to remove the euro sign from my string.
Since the string looks like this €33.0000 - €37.5000, I first explode to string on the - after I try to remove the euro sign.
var string = jQuery('#amount').val();
var arr = string.split(' - ');
if(arr[0] == arr[1]){
jQuery(this).find('.last').css("display", "none");
}else{
for(var i=0; i< arr.length; i++){
arr[i].replace('€','');
console.log(arr[i]);
}
}
When I try it on my site, the euro signs aren't removed, when I get the string like this
var string = jQuery('#amount').val().replace("€", "");
Only the first euro sign is removed
.replace() replace only the fisrt occurence with a string, and replace all occurences with a RegExp:
jQuery('#amount').val().replace(/€/g, "")
Try using a regular expression with global replace flag:
"€33.0000 - €37.5000".replace(/€/g,"")
First get rid of the € (Globally), than split the string into Array parts
var noeur = str.replace(/€/g, '');
var parts = noeur.split(" - ");
The problem with your first attempt is that the replace() method returns a new string. It does not alter the one it executes on.
So it should be arr[i] = arr[i].replace('€','');
Also the replace method, by default, replaces the 1st occurrence only.
You can use the regular expression support and pass the global modifier g so that it applies to the whole string
var string = Query('#amount').val().replace(/€/g, "");
var parts = /^€([0-9.]+) - €([0-9.]+)$/.exec(jQuery('#amount').val()), val1, val2;
if (parts) {
val1 = parts[1];
val2 = parts[2];
} else {
// there is an error in your string
}
You can also tolerate spaces here and there: /^\s*€\s*([0-9.]+)\s*-\s*€\s*([0-9.]+)\s*$/

JS split() function that ignores separator appearing inside quotation marks

Basically, like if you were to say
var string = 'he said "Hello World"';
var splitted = string.split(" ");
the splitted array would be:
'he' 'said' '"Hello World"'
basically treating the quotation mark'd portion as a separate item
So how would I do this in javascript? Would I have to have a for loop that goes over the string checking if the scanner is inside a set of quotation marks? Or is there a simpler way?
You could use regular expressions:
var splitted = string.match(/(".*?")|(\S+)/g);
Basically it searches at first for strings with any characters between quotes (including spaces), and then all the remaining words in the string.
For example
var string = '"This is" not a string "without" "quotes in it"';
string.match(/(".*?")|(\S+)/g);
Returns this to the console:
[""This is"", "not", "a", "string", ""without"", ""quotes in it""]
First of all, I think you mean this:
var string = 'he said "Hello World"';
Now that we've got that out of the way, you were partially correct with your idea of a for loop. Here's how I would do it:
// initialize the variables we'll use here
var string = 'he said "Hello World"', splitted = [], quotedString = "", insideQuotes = false;
string = string.split("");
// loop through string in reverse and remove everything inside of quotes
for(var i = string.length; i >= 0; i--) {
// if this character is a quote, then we're inside a quoted section
if(string[i] == '"') {
insideQuotes = true;
}
// if we're inside quotes, add this character to the current quoted string and
// remove it from the total string
if(insideQuotes) {
if(string[i] == '"' && quotedString.length > 0) {
insideQuotes = false;
}
quotedString += string[i];
string.splice(i, 1);
}
// if we've just exited a quoted section, add the quoted string to the array of
// quoted strings and set it to empty again to search for more quoted sections
if(!insideQuotes && quotedString.length > 0) {
splitted.push(quotedString.split("").reverse().join(""));
quotedString = "";
}
}
// rejoin the string and split the remaining string (everything not in quotes) on spaces
string = string.join("");
var remainingSplit = string.split(" ");
// get rid of excess spaces
for(var i = 0; i<remainingSplit.length; i++) {
if(remainingSplit[i].length == " ") {
remainingSplit.splice(i, 1);
}
}
// finally, log our splitted string with everything inside quotes _not_ split
splitted = remainingSplit.concat(splitted);
console.log(splitted);​
I'm sure there are more efficient ways, but this produces an output exactly like what you specified. Here's a link to a working version of this in jsFiddle.

Categories