Getting strings between two specific occurrences of specific characters in JS - javascript

I am working on the following code. How can I extract/get strings between to specific numbers of characters in an string like
lorem1-lorem9-lorem3-lorem8-lorem1-lorem11-one-two-three-lorem22-lorem55.png?
What I need is:
one-two-three
I am able to remove things after the 9 occurrence of the - but not sure how to remove things before the 6 occurrence of - as well
var str = "lorem1-lorem9-lorem3-lorem8-lorem1-lorem11-one-two-three-lorem22-lorem55.png"
console.log(str.split("-", 9).join("-"));

Array.prototype.splice can be used to split an array.
var str = "lorem1-lorem9-lorem3-lorem8-lorem1-lorem11-one-two-three-lorem22-lorem55.png"
let out = str.split("-", 9).splice(6).join("-")
console.log(out);

Related

How to remove strings before nth character in a text?

I have a dynamically generated text like this
xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0
How can I remove everything before Map ...? I know there is a hard coded way to do this by using substring() but as I said these strings are dynamic and before Map .. can change so I need to do this dynamically by removing everything before 4th index of - character.
You could remove all four minuses and the characters between from start of the string.
var string = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0',
stripped = string.replace(/^([^-]*-){4}/, '');
console.log(stripped);
I would just find the index of Map and use it to slice the string:
let str = "xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0"
let ind = str.indexOf("Map")
console.log(str.slice(ind))
If you prefer a regex (or you may have occurrences of Map in the prefix) you man match exactly what you want with:
let str = "xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0"
let arr = str.match(/^(?:.+?-){4}(.*)/)
console.log(arr[1])
I would just split on the word Map and take the first index
var splitUp = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0'.split('Map')
var firstPart = splitUp[0]
Uses String.replace with regex expression should be the popular solution.
Based on the OP states: so I need to do this dynamically by removing everything before 4th index of - character.,
I think another solution is split('-') first, then join the strings after 4th -.
let test = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0'
console.log(test.split('-').slice(4).join('-'))

How can I split the word by numbers but also keep the numbers in Node.js?

I would like to split a word by numbers, but at the same time keep the numbers in node.js.
For example, take this following sentence:
var a = "shuan3jia4";
What I want is:
"shuan3 jia4"
However, if you use a regexp's split() function, the numbers that are used on the function are gone, for example:
s.split(/[0-9]/)
The result is:
[ 'shuan', 'jia', '' ]
So is there any way to keep the numbers that are used on the split?
You can use match to actually split it per your requirement:
var a = "shuan3jia4";
console.log(a.match(/[a-z]+[0-9]/ig));
use parenthesis around the match you wanna keep
see further details at Javascript and regex: split string and keep the separator
var s = "shuan3jia4";
var arr = s.split(/([0-9])/);
console.log(arr);
var s = "shuan3jia4";
var arr = s.split(/(?<=[0-9])/);
console.log(arr);
This will work as per your requirements. This answer was curated from #arhak and C# split string but keep split chars / separators
As #codybartfast said, (?<=PATTERN) is positive look-behind for PATTERN. It should match at any place where the preceding text fits PATTERN so there should be a match (and a split) after each occurrence of any of the characters.
Split, map, join, trim.
const a = 'shuan3jia4';
const splitUp = a.split('').map(function(char) {
if (parseInt(char)) return `${char} `;
return char;
});
const joined = splitUp.join('').trim();
console.log(joined);

Extract Twitter handlers from string using regex in JavaScript

I Would like to extract the Twitter handler names from a text string, using a regex. I believe I am almost there, except for the ">" that I am including in my output. How can I change my regex to be better, and drop the ">" from my output?
Here is an example of a text string value:
"PlaymakersZA, Absa, DiepslootMTB"
The desired output would be an array consisting of the following:
PlaymakersZA, Absa, DiepslootMTB
Here is an example of my regex:
var array = str.match(/>[a-z-_]+/ig)
Thank you!
You can use match groups in your regex to indicate the part you wish to extract.
I set up this JSFiddle to demonstrate.
Basically, you surround the part of the regex that you want to extract in parenthesis: />([a-z-_]+)/ig, save it as an object, and execute .exec() as long as there are still values. Using index 1 from the resulting array, you can find the first match group's result. Index 0 is the whole regex, and next indices would be subsequent match groups, if available.
var str = "PlaymakersZA, Absa, DiepslootMTB";
var regex = />([a-z-_]+)/ig
var array = regex.exec(str);
while (array != null) {
alert(array[1]);
array = regex.exec(str);
}
You could just strip all the HTML
var str = "PlaymakersZA, Absa, DiepslootMTB";
$handlers = str.replace(/<[^>]*>|\s/g,'').split(",");

How to split a string by a character not directly preceded by a character of the same type?

Let's say I have a string: "We.need..to...split.asap". What I would like to do is to split the string by the delimiter ., but I only wish to split by the first . and include any recurring .s in the succeeding token.
Expected output:
["We", "need", ".to", "..split", "asap"]
In other languages, I know that this is possible with a look-behind /(?<!\.)\./ but Javascript unfortunately does not support such a feature.
I am curious to see your answers to this question. Perhaps there is a clever use of look-aheads that presently evades me?
I was considering reversing the string, then re-reversing the tokens, but that seems like too much work for what I am after... plus controversy: How do you reverse a string in place in JavaScript?
Thanks for the help!
Here's a variation of the answer by guest271314 that handles more than two consecutive delimiters:
var text = "We.need.to...split.asap";
var re = /(\.*[^.]+)\./;
var items = text.split(re).filter(function(val) { return val.length > 0; });
It uses the detail that if the split expression includes a capture group, the captured items are included in the returned array. These capture groups are actually the only thing we are interested in; the tokens are all empty strings, which we filter out.
EDIT: Unfortunately there's perhaps one slight bug with this. If the text to be split starts with a delimiter, that will be included in the first token. If that's an issue, it can be remedied with:
var re = /(?:^|(\.*[^.]+))\./;
var items = text.split(re).filter(function(val) { return !!val; });
(I think this regex is ugly and would welcome an improvement.)
You can do this without any lookaheads:
var subject = "We.need.to....split.asap";
var regex = /\.?(\.*[^.]+)/g;
var matches, output = [];
while(matches = regex.exec(subject)) {
output.push(matches[1]);
}
document.write(JSON.stringify(output));
It seemed like it'd work in one line, as it did on https://regex101.com/r/cO1dP3/1, but had to be expanded in the code above because the /g option by default prevents capturing groups from returning with .match (i.e. the correct data was in the capturing groups, but we couldn't immediately access them without doing the above).
See: JavaScript Regex Global Match Groups
An alternative solution with the original one liner (plus one line) is:
document.write(JSON.stringify(
"We.need.to....split.asap".match(/\.?(\.*[^.]+)/g)
.map(function(s) { return s.replace(/^\./, ''); })
));
Take your pick!
Note: This answer can't handle more than 2 consecutive delimiters, since it was written according to the example in the revision 1 of the question, which was not very clear about such cases.
var text = "We.need.to..split.asap";
// split "." if followed by "."
var res = text.split(/\.(?=\.)/).map(function(val, key) {
// if `val[0]` does not begin with "." split "."
// else split "." if not followed by "."
return val[0] !== "." ? val.split(/\./) : val.split(/\.(?!.*\.)/)
});
// concat arrays `res[0]` , `res[1]`
res = res[0].concat(res[1]);
document.write(JSON.stringify(res));

How to find multiple values between two character in a string - JS

I have a string that I am trying to retrieve a value from between two certain characters. I know there are multiple questions like this on here, but I couldn't find one that searches for multiple instances of this scenario in the same string.
Essentially I have a string like this:
'(value one is: 100), (value two is:200)'
and I want to return both 100 and 200. I know that I can write a regex to retrieve content between two characters, but what is the best way to have a function iterate over the string for the : character and grab everything from that until the ) character and only stop when there are no more instances?
Thanks in advance!
For your case, you can use regex to get the numbers from string.
var str = '(value one is: 100), (value two is:200)';
var regex = /\d+/g;
str.match(regex);
Here \d+ will match the numbers from string. g is global flag to match all the elements and not the only first.
Demo: http://jsfiddle.net/tusharj/k96y3evL/
Using Regex
var regex = /\d+/g;
var string = '(value one is: 100), (value two is:200)';
var match = string.match(regex);
alert(match);
Fiddle

Categories

Resources