How to split javascript string into a max of 2 parts? - javascript

I have strings like this
FOO hello world
BAR something else
BISCUIT is tasty
CAKE is tasty too
The goal is to split string once after the first word. So far I'm using this
# coffeescript
raw = 'FOO hello world'
parts = raw.split /\s/
[command, params] = [parts.shift(), parts.join(' ')]
command #=> FOO
params #=> hello world
I don't like this for two reasons:
It seems inefficient
I'm rejoining the string with a ' ' character. The real string parameters can be split by either a ' ' or a \t and I'd like to leave the originals intact.
Any ideas?

Try this out:
[ command, params ] = /^([^\s]+)\s(.*)$/.exec('FOO hello world').slice(1);

You can use indexOf to find the space (for \t - handle it separately and choose the smaller of the two indexes) and then slice there:
var command;
var params = '';
var space = raw.indexOf(" ");
if(space == -1) {
command = e.data;
} else {
command = raw.slice(0, space);
params = raw.slice(space + 1);
}
Also, it's a lot quicker, as it doesn't uses regular expressions.

Variant of #NathanWall's answer without unnecessary variable:
[command, params] = /([^\s]+)\s(.+)/.exec('FOO hello world').slice(1)

Here a simple code :
var t = "FOO hello world";
var part1 = t.match(/(\w+\s)/)[0];
var part2 = t.replace(part1,"");
part1 will contain "FOO " and part2 "hello world"

Here's how I would do it:
let raw = "FOO hello world"
raw.split(" ")
.filter((part, index) => index !== 0)
.join(" ")
Baically, take the word, split it by the space (or whatever), then filter the first one away, then join it back up.
I find this more intuitive than doing the slicing above.

Another option is:
# coffeescript
raw = 'FOO hello world'
[command, params] = raw.split(/\s/, 2)
command #=> FOO
params #=> hello world
Which I thin't looks more semantic than your original code.

Related

Convert End Quote to Apostrophe Javascript

The below two strings have different apostrophes. I am pretty stumped on how to convert them so that they are the same style (both are either slanted or both are either straight up and down). I have tried everything from enclosing it in `${}`` to regex expressions to remove and replace. I am not sure how it is being stored like this but when I try to search for string1 inside of string2 it doesn't recognize the index because (I believe) of the mismatch apostrophe. Has anyone run into this before?
//let textData = Father’s
//let itemData = Father's Day
const newData = currData.filter(item => {
let itemData = `${item.activityName.toUpperCase()}`;
let textData = `${text.toUpperCase()}`; //coming in slanted
let newItemData = itemData.replace(/"/g, "'");
let newTextData = textData.replace(/"/g, "'");
return newItemData.indexOf(newTextData) > -1;
});
first of all, your code won't run because you are not wrapping your string variables with ", ' or `, depending on the case.
if your string has ' you can use " or ` like this:
"Hello, I'm a dev"
or
"Hello, I`m a dev"
but you can not mix them if you have the same symbol, so this is not allowed:
'Hello, I`m a dev'
here you have a working example of your strings wrapped correctly and also replacing the values to match the strings.
note: please look that the index in this case is 0 because the whole string that we are looking matches from the 0 index to the length of the response1.
also I added a case if you want to get the partial string from string2 based on the match of string1
let string1 = "FATHER’S"
let string2 = "FATHER'S DAY: FOR THE FIXER"
const regex = /’|'/;
const replacer = "'";
let response1 = string1.replace(regex, replacer);
let response2 = string2.replace(regex, replacer);
console.log(response1);
console.log(response2);
console.log("this is your index --> ", response2.indexOf(response1));
console.log("string 2 without string 1 -->", response2.slice(response2.indexOf(response1) + response1.length, response2.length))
You could do a search using a regex, allowing for whatever apostrophe variations you expect:
let string1 = "FATHER’S"
let string2 = "FATHER'S DAY: FOR THE FIXER"
const regex = string1.split(/['’"`]/).join("['’\"`]")
//console.log(regex);
const r = new RegExp(regex)
console.log(string2.search(r)); //comes back as 0

How to get all the strings after a specific index?

Suppose I have this string: /ban 1d hello world which is essentially a command sended to a bot, meaning:
/ban specify to ban the user
1d represents the time
hello world is the reason
I need to get the reason, so I did:
let c = '/ban 1d hello world';
let arr = c.split(' ');
let result = c.replace(arr[0], '');
result = result.replace(arr[1], '')
alert(result);
this is working, but I would like to ask if there is a better way to achieve this.
Kind regards.
If you know that your reason will always be after the second space, you can do something like:
const c = '/ban 1d hello world';
const reason = c.split(' ').slice(2).join(' ');
A regular expression is a good way to match a known format.
You can match against a slash \/ followed by two words separated by spaces \S+ \S+ and then match the remaining characters (.*).
let c = '/ban 1d hello world';
let match = /\/\S+ \S+ (.*)/.exec(c);
let result = match[1];
console.log(result);
If you know the concrete format of the command parts, you could use a regex to get each individual part this way:
let c = '/ban 1d hello world';
var regex = /\/([a-z]+)\ ([0-9]+[a-z])\ (.*)/g;
var resultArray = regex.exec(c);
console.log(resultArray);
let command = resultArray[1] //ban
let time = resultArray[2]; //1d
let result = resultArray[3]; //hello world
console.log(result);

How to search strings with brackets using Regular expressions

I have a case wherein I want to search for all Hello (World) in an array. Hello (World) is coming from a variable and can change. I want to achieve this using RegExp and not indexOf or includes methods.
testArray = ['Hello (World', 'Hello (World)', 'hello (worlD)']
My match should return index 1 & 2 as answers.
Use the RegExp constructor after escaping the string (algorithm from this answer), and use some array methods:
const testArray = ['Hello (World', 'Hello (World)', 'hello (worlD)'];
const string = "Hello (World)".replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
const regex = new RegExp(string, "i");
const indexes = testArray.map((e, i) => e.match(regex) == null ? null : i).filter(e => e != null);
console.log(indexes);
This expression might help you to do so:
(\w+)\s\((\w+)
You may not need to bound it from left and right, since your input strings are well structured. You might just focus on your desired capturing groups, which I have assumed, each one is a single word, which you can simply modify that.
With a simple string replace you can match and capture both of them.
RegEx Descriptive Graph
This graph shows how the expression would work and you can visualize other expressions in this link:
Performance Test
This JavaScript snippet shows the performance of that expression using a simple 1-million times for loop.
repeat = 1000000;
start = Date.now();
for (var i = repeat; i >= 0; i--) {
var string = "Hello (World";
var regex = /(\w+)\s\((\w+)/g;
var match = string.replace(regex, "$1 & $2");
}
end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match 💚💚💚 ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");
testArray = ['Hello (World', 'Hello (World)', 'hello (worlD)'];
let indexes = [];
testArray.map((word,i)=>{
if(word.match(/\(.*\)/)){
indexes.push(i);
}
});
console.log(indexes);

How to remove underscore from beginning of string

I need to remove underscores from the beginning of a string(but only the beginning),
For example:
__Hello World
Should be converted to :
Hello World
But Hello_World should stay as Hello_World.
Tricky thing is I don't know how may underscores there could be 1,2 or 20.
You can pass a regex to replace(). /^_+/, says find any number of _ after at the beginning of the string:
let texts = ["__Hello World", "Hello_World", 'jello world_', '_Hello_World_', '___________Hello World']
let fixed = texts.map(t => t.replace(/^_+/, ''))
console.log(fixed)
Regex is pretty suited for this task:
let str = "__h_e_l_l_o__"
console.log(str.replace(/^_*/, ""));
Method 01:
var str = '__Hello World';
str = str.replace(/^_*/, "");
Method 02:
var str = '__Hello World';
while(str.startsWith('_')){
str = str.replace('_','');
}
console.log(str);
// Hello World

Turn string into object

Okay so I know
var str = {}; string.split(' ').forEach(function(val, idx) {str[++idx] = val;});
but if string was " Hello world 'how r u' " it would return
["1":"Hello","2":"world","3":"how","4":"r","5":"u"]
I want it to return
["1":"Hello","2":"world","3":"how r u"]
so things between ' ' and " " are 1 item how do I make it do that?
btw I'm using node.js
Not a node.js guru, so I don't know if there is a nice solution by means of regular expressions in the split function, but a solution might be to write a function to first split up the original string into bigger chunk, based on the " or ' character. This will result in an array of strings, which you can then further split up into smaller chunks.
Thank you louis on swiftirc#javascript for this
var out = {}; 'this is "a test" with a "random string of words" 34iuv 38vy 3b8u nuhvbe7yvb 73rvy dsuh bue "f34fdvedfg wr edf Fw efwef" efg3f'.match(/\w+|"(.[^"]+)"/g).forEach(function (str, idx) { out[++idx] = str.replace(/^"|"$/g,''); });
console.log(out);
>> {"1":"this","2":"is","3":"a test","4":"with","5":"a","6":"random string of words","7":"34iuv","8":"38vy","9":"3b8u","10":"nuhvbe7yvb","11":"73rvy","12":"dsuh","13":"bue","14":"f34fdvedfg wr edf Fw efwef","15":"efg3f"}

Categories

Resources