Splitting string from the first occurrence of a character - javascript

I have multiple lines of text in log files in this kind of format:
topic, this is the message part, with, occasional commas.
How can I split the string from the first comma so I would have the topic and the rest of the message in two different variables?
I've tried using this kind of split, but it doesn't work when there's more commas in the message part.
[topic, message] = whole_message.split(",", 2);

Use a regex that gets "everything but the first comma". So:
whole_message.match(/([^,]*),(.*)/)
[1] will be the topic, [2] will be the message.

That sort of decomposing assignment doesn't work in Javascript (at the present time). Try this:
var split = whole_message.split(',', 2);
var topic = split[0], message = split[1];
edit — ok so "split()" is kind-of broken; try this:
var topic, message;
whole_message.replace(/^([^,]*)(?:,(.*))?$/, function(_, t, m) {
topic = t; message = m;
});

Here!
String.prototype.mySplit = function(char) {
var arr = new Array();
arr[0] = this.substring(0, this.indexOf(char));
arr[1] = this.substring(this.indexOf(char) + 1);
return arr;
}
str = 'topic, this is the message part, with, occasional commas.'
str.mySplit(',');
-> ["topic", " this is the message part, with, occasional commas."]

javascript's String.split() method is broken (at least if you're expecting the same behavior that other language's split() methods provide).
An example of this behavior:
console.log('a,b,c'.split(',', 2))
> ['a', 'b']
and not
> ['a', 'b,c']
like you'd expect.
Try this split function instead:
function extended_split(str, separator, max) {
var out = [],
index = 0,
next;
while (!max || out.length < max - 1 ) {
next = str.indexOf(separator, index);
if (next === -1) {
break;
}
out.push(str.substring(index, next));
index = next + separator.length;
}
out.push(str.substring(index));
return out;
};

var a = whole_message.split(",");
var topic = a.splice (0,1);
(unless you like doing things complicated ways)

Why not split by comma, take the [0] item as topic then remove the topic(+,) from the original string ?
You could:
var topic = whole_message.split(",")[0]
(using prototype.js)
var message = whole_message.gsub(topic+", ", "")
(using jQuery)
whole_message.replace(topic+", ", "")
Or quicker, go with josh.trow

let string="topic, this is the message part, with occasional commas."
let arr = new Array();
let idx = string.indexOf(',')
arr[0] = string.substring(0, idx);
arr[1] = string.substring(idx+1);
let topic = arr[0];
let message = arr[1]
output arr should be: ["topic", "this is the message part, with occasional commas."]

Related

Regex matching dates in a string in Javascript

Following up from this thread, im trying to make this work
JavaScript regular expression to match X digits only
string = '2016-2022'
re = /\d{4}/g
result = [...string.matchAll(re)]
This returns an array of two arrays. Is there a way to consolidate this into 1 array?
However it doesn't look like this is returning the desired results
I'm new to regular expression. What am I doing wrong?
this return an array of matches
result = string.match(re)
This is a function to parse the string encoding those two year values and return the inner years as items of an array:
let o = parseYearsInterval('2016-2022');
console.log(o);
function parseYearsInterval(encodedValue){
var myregexp = /(\d{4})-(\d{4})/;
var match = myregexp.exec(encodedValue);
if (match != null) {
let d1 = match[1];
let d2 = match[2];
//return `[${d1}, ${d2}]`;
let result = [];
result.push(d1);
result.push(d2);
return result;
} else {
return "not valid input";
}
}
I think there are better ways to do that like splitting the string against the "-" separator and return that value as is like:
console.log ( "2016-2022".split('-') )
Just do a split if you know that only years are in the string and the strucutre isn't changing:
let arr = str.split("-");
Question
string = '2016-2022'
re = /\d{4}/g
result = [...string.matchAll(re)]
This returns an array of two arrays. Is there a way to consolidate
this into 1 array?
Solution
You may simply flat the result of matchAll.
let string = '2016-2022'
let re = /\d{4}/g
console.log([...string.matchAll(re)].flat())
Alternative
If your structure is given like "yyyy-yyyy-yyyy" you might consider a simple split
console.log('2016-2022'.split('-'))
var str = '2016-2022';
var result = [];
str.replace(/\d{4}/g, function(match, i, original) {
result.push(match);
return '';
});
console.log(result);
I also wanted to mention, that matchAll does basicly nothing else then an while exec, that's why you get 2 arrays, you can do it by yourself in a while loop and just save back what you need
var result = [];
var matches;
var regexp = /\d{4}/g;
while (matches = regexp.exec('2016-2022')) result.push(matches[0]);
console.log(result);

Editing a string using regex jquery [duplicate]

i have comma separated string like
var test = 1,3,4,5,6,
i want to remove particular character from this string using java script
can anyone suggests me?
JavaScript strings provide you with replace method which takes as a parameter a string of which the first instance is replaced or a RegEx, which if being global, replaces all instances.
Example:
var str = 'aba';
str.replace('a', ''); // results in 'ba'
str.replace(/a/g, ''); // results in 'b'
If you alert str - you will get back the same original string cause strings are immutable.
You will need to assign it back to the string :
str = str.replace('a', '');
Use replace and if you want to remove multiple occurrence of the character use
replace like this
var test = "1,3,4,5,6,";
var newTest = test.replace(/,/g, '-');
here newTest will became "1-3-4-5-6-"
you can make use of JavaScript replace() Method
var str="Visit Microsoft!";
var n=str.replace("Microsoft","My Blog");
var test = '1,3,4,5,6';​​
//to remove character
document.write(test.replace(/,/g, ''));
//to remove number
function removeNum(string, val){
var arr = string.split(',');
for(var i in arr){
if(arr[i] == val){
arr.splice(i, 1);
i--;
}
}
return arr.join(',');
}
var str = removeNum(test,3);
document.write(str); // output 1,4,5,6
You can also
var test1 = test.split(',');
delete test1[2];
var test2 = test1.toString();
Have fun :)
you can split the string by comma into an array and then remove the particular element [character or number or even string] from that array. once the element(s) removed, you can join the elements in the array into a string again
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
You can use this function
function removeComma(inputNumber,char='') {
return inputNumber.replace(/,/g, char);
}
Update
function removeComma(inputNumber) {
inputNumber = inputNumber.toString();
return Number(inputNumber.replace(/,/g, ''));
}

How to capitalize the last letter of each word in a string

I am still rather new to JavaScript and I am having an issue of getting the first character of the string inside the array to become uppercase.
I have gotten to a point where I have gotten all the texted lowercase, reversed the text character by character, and made it into a string. I need to get the first letter in the string to uppercase now.
function yay () {
var input = "Party like its 2015";
return input.toLowerCase().split("").reverse().join("").split(" ");
for(var i = 1 ; i < input.length ; i++){
input[i] = input[i].charAt(0).toUpperCase() + input[i].substr(1);
}
}
console.log(yay());
I need the output to be "partY likE itS 2015"
Frustrating that you posted your initial question without disclosing the desired result. Lots of turmoil because of that. Now, that the desired result is finally clear - here's an answer.
You can lowercase the whole thing, then split into words, rebuild each word in the array by uppercasing the last character in the word, then rejoin the array:
function endCaseWords(input) {
return input.toLowerCase().split(" ").map(function(item) {
return item.slice(0, -1) + item.slice(-1).toUpperCase();
}).join(" ");
}
document.write(endCaseWords("Party like its 2015"));
Here's a step by step explanation:
Lowercase the whole string
Use .split(" ") to split into an array of words
Use .map() to iterate the array
For each word, create a new word that is the first part of the word added to an uppercased version of the last character in the word
.join(" ") back together into a single string
Return the result
You could also use a regex replace with a custom callback:
function endCaseWords(input) {
return input.toLowerCase().replace(/.\b/g, function(match) {
return match.toUpperCase();
});
}
document.write(endCaseWords("Party like its 2015"));
FYI, there are lots of things wrong with your original code. The biggest mistake is that as soon as you return in a function, no other code in that function is executed so your for loop was never executed.
Then, there's really no reason to need to reverse() the characters because once you split into words, you can just access the last character in each word.
Instead of returning the result splitting and reversing the string, you need to assign it to input. Otherwise, you return from the function before doing the loop that capitalizes the words.
Then after the for loop you should return the joined string.
Also, since you've reverse the string before you capitalize, you should be capitalizing the last letter of each word. Then you need to reverse the array before re-joining it, to get the words back in the original order.
function yay () {
var input = "Party like its 2015";
input = input.toLowerCase().split("").reverse().join("").split(" ");
for(var i = 1 ; i < input.length ; i++){
var len = input[i].length-1;
input[i] = input[i].substring(0, len) + input[i].substr(len).toUpperCase();
}
return input.reverse().join(" ");
}
alert(yay());
You can use regular expression for that:
input.toLowerCase().replace(/[a-z]\b/g, function (c) { return c.toUpperCase() });
Or, if you can use arrow functions, simply:
input.toLowerCase().replace(/[a-z]\b/g, c => c.toUpperCase())
Here's what I would do:
Split the sentence on the space character
Transform the resulting array using .map to capitalize the first character and lowercase the remaining ones
Join the array on a space again to get a string
function yay () {
var input = "Party like its 2015";
return input.split(" ").map(function(item) {
return item.charAt(0).toUpperCase() + item.slice(1).toLowerCase();
}).join(" ");
}
console.log(yay());
Some ugly, but working code:
var text = "Party like its 2015";
//partY likE itS 2015
function yay(input) {
input = input.split(' ');
arr = [];
for (i = 0; i < input.length; i++) {
new_inp = input[i].charAt(0).toLowerCase() + input[i].substring(1, input[i].length - 1) + input[i].charAt(input[i].length - 1).toUpperCase();
arr.push(new_inp);
}
str = arr.join(' ');
return str;
}
console.log(yay(text));
Try using ucwords from PHP.js. It's quite simple, actually.
String.prototype.ucwords = function() {
return (this + '')
.replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function($1) {
return $1.toUpperCase();
});
}
var input = "Party like its 2015";
input = input.charAt(0).toLowerCase() + input.substr(1);
input = input.split('').reverse().join('').ucwords();
input = input.split('').reverse().join('');
Note: I modified their function to be a String function so method chaining would work.
function yay(str)
{
let arr = str.split(' ');
let farr = arr.map((item) =>{
let x = item.split('');
let len = x.length-1
x[len] = x[len].toUpperCase();
x= x.join('')
return x;
})
return farr.join(' ')
}
var str = "Party like its 2015";
let output = yay(str);
console.log(output) /// "PartY likE itS 2015"
You can split and then map over the array perform uppercase logic and retun by joining string.
let string = "Party like its 2015";
const yay = (string) => {
let lastCharUpperCase = string.split(" ").map((elem) => {
elem = elem.toLowerCase();
return elem.replace(elem[elem.length - 1], elem[elem.length - 1].toUpperCase())
})
return lastCharUpperCase.join(" ");
}
console.log(yay(string))

split string and leave the separators intact

I cannot find a good way to split a string using a separator string but leave the separator as the prefix of each element of the resulting array:
from
var s = 'blah0__blah1__blah2';
I need to get
['blah0', '__blah1', '__blah2']
the closest thing that I could get was
s.split(/(__)/);
which returns
['blah0', '__', 'blah1', '__', 'blah2']
but this I would need to traverse to merge the underscores.
Is there a better way?
EDIT:
here is my best effort so far:
'blah__blah1__blah2'.split(/(__[^_]+)/)
// => ["blah", "__blah1", "", "__blah2", ""]
still, there are empty strings in the output...
How about this:
var s = 'blah0__blah__blah'
var s_split = s.match(/(__)?(.(?!__))+./g)
console.log(s_split)
I'm pretty sure it's much more costly (time and memory wise) than simply reiterating and joining after a regular split.
If you replace __ with your separator it should work fine for most cases.
A two-step process.
var s = 'blah0__blah1__blah2';
var blahs = s.split('__');
var scoreBlahs = blahs.map(preScore);
alert(scoreBlahs);
function preScore(b) {
var x;
var result = x.concat('__',b);
return result;
}
'blah0__blah1__blah2'.match(/^[^_]+|_+[^_]+/g);
["blah0", "__blah1", "__blah2"]
Seems to give you what you want. Though It may vary, if your input isn't exactly as you show it.
Just prepend the seperator after you seperate the string
var value = "a,b,c";
var splitter = value.split(",");
for(var i = 0; i < splitter.length; i++) {
alert("," + splitter[i]);
}
Since you know the separator - just add it again later on:
var s = 'blah0__blah1__blah2';
var sep = '__';
var arr = s.split(sep);
for (var i = 1; i < arr.length; i++) {
arr[i] = sep + arr[i];
}
console.log(arr);
You could insert a secondary separator, and split on that, leaving the original intact.
var s = 'blah0__blah1__blah2';
s = s.replace('_', '_$');
s.split('$');

Cutting a string at nth occurrence of a character

What I want to do is take a string such as "this.those.that" and get a substring to or from the nth occurrence of a character. So, from the start of the string to the 2nd occurrence of . would return "this.those". Likewise, from the 2nd occurrence of . to the end of the string would return "that". Sorry if my question is foggy, it's not that easy to explain. Also, please do not suggest making extra variables, and the result will be in a string and not an array.
You could do it without arrays, but it would take more code and be less readable.
Generally, you only want to use as much code to get the job done, and this also increases readability. If you find this task is becoming a performance issue (benchmark it), then you can decide to start refactoring for performance.
var str = 'this.those.that',
delimiter = '.',
start = 1,
tokens = str.split(delimiter).slice(start),
result = tokens.join(delimiter); // those.that
console.log(result)
// To get the substring BEFORE the nth occurence
var tokens2 = str.split(delimiter).slice(0, start),
result2 = tokens2.join(delimiter); // this
console.log(result2)
jsFiddle.
Try this :
"qwe.fs.xczv.xcv.xcv.x".replace(/([^\.]*\.){3}/, '');
"xcv.xcv.x"
"qwe.fs.xczv.xcv.xcv.x".replace(/([^\.]*\.){**nth**}/, ''); - where is nth is the amount of occurrence to remove.
I'm perplexed as to why you want to do things purely with string functions, but I guess you could do something like the following:
//str - the string
//c - the character or string to search for
//n - which occurrence
//fromStart - if true, go from beginning to the occurrence; else go from the occurrence to the end of the string
var cut = function (str, c, n, fromStart) {
var strCopy = str.slice(); //make a copy of the string
var index;
while (n > 1) {
index = strCopy.indexOf(c)
strCopy = strCopy.substring(0, index)
n--;
}
if (fromStart) {
return str.substring(0, index);
} else {
return str.substring(index+1, str.length);
}
}
However, I'd strongly advocate for something like alex's much simpler code.
Just in case somebody needs both "this" and "those.that" in a way as alex described in his comment, here is a modified code:
var str = 'this.those.that',
delimiter = '.',
start = 1,
tokens = str.split(delimiter),
result = [tokens.slice(0, start), tokens.slice(start)].map(function(item) {
return item.join(delimiter);
}); // [ 'this', 'those.that' ]
document.body.innerHTML = result;
If you really want to stick to string methods, then:
// Return a substring of s upto but not including
// the nth occurence of c
function getNth(s, c, n) {
var idx;
var i = 0;
var newS = '';
do {
idx = s.indexOf(c);
newS += s.substring(0, idx);
s = s.substring(idx+1);
} while (++i < n && (newS += c))
return newS;
}

Categories