Search in string and quote around occurrence - javascript

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

Related

Using regex, extract values from a string in javascript

Need to extract values from a string using regex(for perf reasons).
Cases might be as follows:
RED,100
RED,"100"
RED,"100,"
RED,"100\"ABC\"200"
The resulting separated [label, value] array should be:
['RED','100']
['RED','100']
['RED','100,']
['RED','100"ABC"200']
I looked into solutions and a popular library even, just splits the entire string to get the values,
e.g. 'RED,100'.split(/,/) might just do the thing.
But I was trying to make a regex with comma, which splits only if that comma is not enclosed within a quotes type value.
This isnt a standard CSV behaviour might be. But its very easy for end-user to enter values.
enter label,value. Do whatever inside value, if thats surrounded by quotes. If you wanna contain quotes, use a backslash.
Any help is appreciated.
You can use this regex that takes care of escaped quotes in string:
/"[^"\\]*(?:\\.[^"\\]*)*"|[^,"]+/g
RegEx Explanation:
": Match a literal opening quote
[^"\\]*: Match 0 or more of any character that is not \ and not a quote
(?:\\.[^"\\]*)*: Followed by escaped character and another non-quote, non-\. Match 0 or more of this combination to get through all escaped characters
": Match closing quote
|: OR (alternation)
[^,"]+: Match 1+ of non-quote, non-comma string
RegEx Demo
const regex = /"[^"\\]*(?:\\.[^"\\]*)*"|[^,"]+/g;
const arr = [`RED,100`, `RED,"100"`, `RED,"100,"`,
`RED,"100\\"ABC\\"200"`];
let m;
for (var i = 0; i < arr.length; i++) {
var str = arr[i];
var result = [];
while ((m = regex.exec(str)) !== null) {
result.push(m[0]);
}
console.log("Input:", str, ":: Result =>", result);
}
You could use String#match and take only the groups.
var array = ['RED,100', 'RED,"100"', 'RED,"100,"', 'RED,"100\"ABC\"200"'];
console.log(array.map(s => s.match(/^([^,]+),(.*)$/).slice(1)))

How to check if part of string is present in array or not

I have got of array symbols as shown below
var sourcesymbols = ["ERT", "UBL" , "AMAZING"];
I am getting the following news title from rss feed
you experts are amazing
How to check if the content present in the rssfeedstring is present under the sourcesymbols array or not ??
For example rssfeedstring has word amazing and it is also present under sourcesymbols
please let me know how to achive this .
I have tried to convert the rssfeedstring to uppercase then i am not sure how to use the indexOf on the string .
rssfeedstring = rssfeedstring.toUpperCase();
please let em know if there is any better approach also for doing this as the array will have 2000 symbols
http://jsfiddle.net/955pfz01/3/
You can use regex.
Steps:
Convert the array to string with join using |(OR in regex) as glue
Use \b-word boundary to match exact words
Use i flag on regex to match irrespective of the case. So, don't have to change the case of string.
Escape the slashes as using RegExp constructor requires string to be passed and \ in string is used as escape following character.
test can be used on regex to check if the string passes the regex.
var sourcesymbols = ["ERT", "UBL", "AMAZING"];
var mystr = 'you experts are amazing';
var regex = new RegExp("\\b(" + sourcesymbols.join('|') + ")\\b", 'i'); // /\b(ERT|UBL|AMAZING)\b/i
alert(regex.test(mystr));
You can also use some
Convert the string to array by using split with \s+. This will split the string by any(spaces, tabs, etc) one or more space character
Use some on splitted array
Convert the string to uppercase for comparing
Check if the element is present in array using indexOf
var mystr = 'you experts are amazing';
var sourcesymbols = ["ERT", "UBL", "AMAZING"];
var present = mystr.toUpperCase().split(/\s+/).some(function(e) {
return sourcesymbols.indexOf(e) > -1;
});
alert(present);
Try using Array.prototype.map() , Array.prototype.indexOf() to return matched text, index of matched text within sourcesymbols
var sourcesymbols = ["ERT", "UBL" , "AMAZING"];
var mystr = 'you experts are amazing';
var res = mystr.split(" ").map(function(val, index) {
var str = val.toUpperCase(), i = sourcesymbols.indexOf(str);
return i !== -1 ? [val, i] : null
}).filter(Boolean);
console.log(res)
jsfiddle http://jsfiddle.net/955pfz01/6/

Remove (n)th space from string in JavaScript

I am trying to remove some spaces from a few dynamically generated strings. Which space I remove depends on the length of the string. The strings change all the time so in order to know how many spaces there are, I iterate over the string and increment a variable every time the iteration encounters a space. I can already remove all of a specific type of character with str.replace(' ',''); where 'str' is the name of my string, but I only need to remove a specific occurrence of a space, not all the spaces. So let's say my string is
var str = "Hello, this is a test.";
How can I remove ONLY the space after the word "is"? (Assuming that the next string will be different so I can't just write str.replace('is ','is'); because the word "is" might not be in the next string).
I checked documentation on .replace, but there are no other parameters that it accepts so I can't tell it just to replace the nth instance of a space.
If you want to go by indexes of the spaces:
var str = 'Hello, this is a test.';
function replace(str, indexes){
return str.split(' ').reduce(function(prev, curr, i){
var separator = ~indexes.indexOf(i) ? '' : ' ';
return prev + separator + curr;
});
}
console.log(replace(str, [2,3]));
http://jsfiddle.net/96Lvpcew/1/
As it is easy for you to get the index of the space (as you are iterating over the string) , you can create a new string without the space by doing:
str = str.substr(0, index)+ str.substr(index);
where index is the index of the space you want to remove.
I came up with this for unknown indices
function removeNthSpace(str, n) {
var spacelessArray = str.split(' ');
return spacelessArray
.slice(0, n - 1) // left prefix part may be '', saves spaces
.concat([spacelessArray.slice(n - 1, n + 1).join('')]) // middle part: the one without the space
.concat(spacelessArray.slice(n + 1)).join(' '); // right part, saves spaces
}
Do you know which space you want to remove because of word count or chars count?
If char count, you can Rafaels Cardoso's answer,
If word count you can split them with space and join however you want:
var wordArray = str.split(" ");
var newStr = "";
wordIndex = 3; // or whatever you want
for (i; i<wordArray.length; i++) {
newStr+=wordArray[i];
if (i!=wordIndex) {
newStr+=' ';
}
}
I think your best bet is to split the string into an array based on placement of spaces in the string, splice off the space you don't want, and rejoin the array into a string.
Check this out:
var x = "Hello, this is a test.";
var n = 3; // we want to remove the third space
var arr = x.split(/([ ])/); // copy to an array based on space placement
// arr: ["Hello,"," ","this"," ","is"," ","a"," ","test."]
arr.splice(n*2-1,1); // Remove the third space
x = arr.join("");
alert(x); // "Hello, this isa test."
Further Notes
The first thing to note is that str.replace(' ',''); will actually only replace the first instance of a space character. String.replace() also accepts a regular expression as the first parameter, which you'll want to use for more complex replacements.
To actually replace all spaces in the string, you could do str.replace(/ /g,""); and to replace all whitespace (including spaces, tabs, and newlines), you could do str.replace(/\s/g,"");
To fiddle around with different regular expressions and see what they mean, I recommend using http://www.regexr.com
A lot of the functions on the JavaScript String object that seem to take strings as parameters can also take regular expressions, including .split() and .search().

Find last string after delimiter: Javascript

I have a url with many delimiters '/'.
I want to find the string after the last delimiter. How can I write a javascript code?
for eg if my url is
localhost/sample/message/invitation/create/email
I want to display 'email' as my output.
var last = input.split("/").pop();
Simples!
Splitting on a regex that matches spaces or hyphens and taking the last element
var lw = function(v) {
return (""+v).replace(/[\s-]+$/,'').split(/[\s-]/).pop();
};
lw('This is a test.'); // returns 'test.'
lw('localhost/sample/message/invitation/create/email,'); // returns 'email,'
var url="localhost/sample/message/invitation/create/email";
url.split("/").pop()
or
var last=$(url.split("/")).last();
Usng simple regex
var str = "localhost/sample/message/invitation/create/email";
var last = str.match(/[^/]*$/)[0]";
Above regex return all character after last "/"

split string based on a symbol

I'm trying to split a string into an array based on the second occurrence of the symbol _
var string = "this_is_my_string";
I want to split the string after the second underscore. The string is not always the same but it always has 2 or more underscores in it. I always need it split on the second underscore.
In the example string above I would need it to be split like this.
var split = [this_is, _my_string];
var string = "this_is_my_string";
var firstUnderscore = string.indexOf('_');
var secondUnderscore = string.indexOf('_', firstUnderscore + 1);
var split = [string.substring(0, secondUnderscore),
string.substring(secondUnderscore)];
Paste it into your browser's console to try it out. No need for a jsFiddle.
var string = "this_is_my_string";
var splitChar = string.indexOf('_', string.indexOf('_') + 1);
var result = [string.substring(0, splitChar),
string.substring(splitChar, string.length)];
This should work.
var str = "this_is_my_string";
var matches = str.match(/(.*?_.*?)(_.*)/); // MAGIC HAPPENS HERE
var firstPart = matches[1]; // this_is
var secondPart = matches[2]; // _my_string
This uses regular expressions to find the first two underscores, and captures the part up to it and the part after it. The first subexpression, (.*?_.*?), says "any number of characters, an underscore, and again any number of characters, keeping the number of characters matched as small as possible, and capture it". The second one, (_.*) means "match an underscore, then any number of characters, as much of them as possible, and capture it". The result of the match function is an array starting with the full matched region, followed by the two captured groups.
I know this post is quite old... but couldn't help but notice that no one provided a working solution. Here's one that works:
String str = "this_is_my_string";
String undScore1 = str.split("_")[0];
String undScore2 = str.split("_")[1];
String bothUndScores = undScore1 + "_" + undScore2 + "_";
String allElse = str.split(bothUndScores)[1];
System.out.println(allElse);
This is assuming you know there will always be at least 2 underscores - "allElse" returns everything after the second occurrence.

Categories