How to get all the strings after a specific index? - javascript

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

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

Javascript get only matched text in regex

I have string like below
BANKNIFTY-13-FEB-2020-31200-ce
I want to convert the string to 13-FEB-31200-ce
so I tried below code
str.match(/(.*)-(?:.*)-(?:.*)-(.*)-(?:.*)-(?:.*)/g)
But its returning whole string
Two capture groups is probably the way to go. Now you have two options to use it. One is match which requires you to put the two pieces together
var str = 'BANKNIFTY-13-FEB-2020-31200-ce'
var match = str.match(/[^-]+-(\d{2}-[A-Z]{3}-)\d{4}-(.*)/)
// just reference the two groups
console.log(`${match[1]}${match[2]}`)
// or you can remove the match and join the remaining
match.shift()
console.log(match.join(''))
Or just string replace which you do the concatenation of the two capture groups in one line.
var str = 'BANKNIFTY-13-FEB-2020-31200-ce'
var match = str.replace(/[^-]+-(\d{2}-[A-Z]{3}-)\d{4}-(.*)/, '$1$2')
console.log(match)
Regex doesn't seem to be the most appropriate tool here. Why not use simple .split?
let str = 'BANKNIFTY-13-FEB-2020-31200-ce';
let splits = str.split('-');
let out = [splits[1], splits[2], splits[4], splits[5]].join('-');
console.log(out);
If you really want to use regexp,
let str = 'BANKNIFTY-13-FEB-2020-31200-ce';
let splits = str.match(/[^-]+/g);
let out = [splits[1], splits[2], splits[4], splits[5]].join('-');
console.log(out);
I would not use Regex at all if you know exact positions. Using regex is expensive and should be done differently if there is way. (https://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/)
const strArr = "BANKNIFTY-13-FEB-2020-31200-ce".split("-"); // creates array
strArr.splice(0,1); // remove first item
strArr.splice(2,1); // remove 2020
const finalStr = strArr.join("-");
If the pattern doesn't need to be too specific.
Then just keep it simple and only capture what's needed.
Then glue the captured groups together.
let str = 'BANKNIFTY-13-FEB-2020-31200-ce';
let m = str.match(/^\w+-(\d{1,2}-[A-Z]{3})-\d+-(.*)$/)
let result = m ? m[1]+'-'+m[2] : undefined;
console.log(result);
In this regex, ^ is the start of the string and $ the end of the string.
You can have something like this by capturing groups with regex:
const regex = /(\d{2}\-\w{3})(\-\d{4})(\-\d{5}\-\w{2})/
const text = "BANKNIFTY-13-FEB-2020-31200-ce"
const [, a, b, c] = text.match(regex);
console.log(`${a}${c}`)

RegEx - Parse through string for specific words

I'm looking to parse through a string and find all the handles (#name) and push them each into one array (without the # though) so I can loop through them (with forEach) and send them each an alert. Each handle is separated by a space.
If you just need to extract the users from a tweet, you can use the following regex:
/#([a-zA-Z0-9]+)/g
For example:
var string = '#JohnSmith #DylanThompson Hey guys!';
var numberPattern = /#([a-zA-Z0-9]+)/g;
var res = string.match(numberPattern);
console.log(res);
This would spit out:
["#JohnSmith", "#DylanThompson"]
You can capture #followedByName and than replace #
let str = `#someName hey #someMoreNames`
let op = str.match(/(^|\s)#\w+/g).map(e=>e.trim().replace(/#/g,''))
console.log(op)
try
let str= "Here #ann and #john go to #jane";
let m= str.match(/#\w+/g).map(x=>x.replace(/./,''));
m.forEach(x=> console.log(x));
You can use also positive lookbehind regexp but it is not supported by firefox yet (but it is part of ES2018):
let str= "Here #ann and #john go to #jane";
let m= str.match(/(?<=#)\w+/g);
m.forEach(x=> console.log(x));
where (?<=#)\w+ match word which start after # (excluding this char - positive lookbehind)
You can combine match to extract names and slice to remove #:
str = "#JohnSmith #DylanThompson Hey guys";
let arr = str.match(/#\w+/g).map(e=>e.slice(1));
console.log(arr);
Try This:
var str= "Here #ann and #john go to #jane";
var patt = /#(\w+)/g;
while ( (arr = patt.exec(str)) !== null ) { console.log(arr[1]); }

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

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

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.

Categories

Resources