How to get the delimiters that split my string in Javascript? - javascript

Let's say I have a string like the following:
var str = "hello=world&universe";
And my regex replace statement goes like this:
str.replace(/([&=])/g, ' ');
How do I get the delimiters that split my string from the above regex replace statement?
I would like the result to be something like this:
var strings = ['hello', 'world', 'universe'];
var delimiters = ['=', '&'];

You could split with a group and then separate the parts.
var str = "hello=world&universe",
[words, delimiters] = str
.split(/([&=])/)
.reduce((r, s, i) => {
r[i % 2].push(s);
return r;
}, [[], []]);
console.log(words);
console.log(delimiters);

Here's one way using String.matchAll
const str = "hello=world&universe";
const re = /([&=])/g;
const matches = [];
let pos = 0;
const delimiters = [...str.matchAll(re)].map(m => {
const [match, capture] = m;
matches.push(str.substring(pos, m.index));
pos = m.index + match.length;
return match;
});
matches.push(str.substring(pos));
console.log('matches:', matches.join(', '));
console.log('delimiters:', delimiters.join(', '));
But just FYI. The string you posted looks like a URL search string. You probably want to use URLSearchParams to parse it as there are edge cases if you try to split on both '&' and '=' at the same time. See How can I get query string values in JavaScript?

Related

JS String how to extract an array of substring that matches a condition?

I have a string like this:
"|hello| + |world| / |again|"
And I need to get the substrings inside the | and return an array like this:
["hello", "world", "again"]
What is the best approach to accomplish this?
You can use a regex that searches for groups consisting only of letters (([A-Za-z])) between pipes (/|) where the pipes are to omitted from the actual match (wrapped with (?:))-- then use .matchAll to get all the matches and .map the result to get the captured groups only (non-captures omitted) -- see below:
const str = "|hello| + |world| / |again|";
const re = /(?:\|)([A-Za-z]+)(?:\|)/g;
const results = [...str.matchAll(re)].map((entry) => entry[1]);
console.log(results);
This will work to match only those words that are between pipes. If you have other words in your string that are not wrapped between pipes, they will be ignored. Like the following snippet:
const str = "|hello| + |world| / |again| how are |you| doing?";
const re = /(?:\|)([A-Za-z]+)(?:\|)/g;
const results = [...str.matchAll(re)].map((entry) => entry[1]);
console.log(results);
array = [];
let name = "";
let input = "|hello| + |world| / |again|";
let index = 0;
let isStart = false;
while (index < input.length) {
if (input[index] == '|') {
isStart = !isStart;
if (!isStart) {
array.push(name);
name = "";
}
} else {
if (isStart) {
name = name + input[index];
}
}
index++;
}
console.log(array);
If that string doesn't change format use a regular expression to match against multiple lower-case letters.
const str = '|hello| + |world| / |again|';
const regex = /[a-z]+/g;
console.log(str.match(regex));

Replace 2 characters inside a string in JavaScript

I have this string and I want to fill all the blank values with 0 between to , :
var initialString = 3,816,AAA3,aa,cc,bb,5.9,27,46,0.62,29,12,7,10,13.1,86,6.02,20,1.68,8,0.24,48,22,6.2,0.9,,,1,
I want this output :
var finalString = 3,816,AAA3,aa,cc,bb,5.9,27,46,0.62,29,12,7,10,13.1,86,6.02,20,1.68,8,0.24,48,22,6.2,0.9,0,0,1,0
I try to use replace
var newString = initialString.replace(/,,/g, ",0,").replace(/,$/, ",0");
But the finalString looks like this:
var initialString = 3,816,AAA3,aa,cc,bb,5.9,27,46,0.62,29,12,7,10,13.1,86,6.02,20,1.68,8,0.24,48,22,6.2,0.9,0,,1,0
Some coma are not replaced.
Can someone show me how to do it?
You can match a comma which is followed by either a comma or end of line (using a forward lookahead) and replace it with a comma and a 0:
const initialString = '3,816,AAA3,aa,cc,86,6.02,20,1.68,8,0.24,48,22,6.2,0.9,,,1,';
let result = initialString.replace(/,(?=,|$)/g, ',0');
console.log(result)
using split and join
var str = "3,816,AAA3,aa,cc,bb,5.9,27,46,0.62,29,12,7,10,13.1,86,6.02,20,1.68,8,0.24,48,22,6.2,0.9,,,1,";
const result = str
.split(",")
.map((s) => (s === "" ? "0" : s))
.join(",");
console.log(result);

Replace last part of string, javascript

const str = ".1.2.1"
const str2 = ".1";
const func = (str, str2) => {
...
}
expected output = ".1.2"
Another example:
str = "CABC"
str2 = "C"
Expected output "CAB"
So the last part of the string that matches the end of the string should be removed.
Can this be done with some neat build-in-function in javascript?
Update
Updated string example. Simple replace does not work.
Just try replacing \.\d+$ with empty string, using a regex replacement:
var input = "1.2.1";
input = input.replace(/\.\d+$/, "");
console.log(input);
Edit:
Assuming the final portion of the input to be removed is actually contained in a string variable, then we might be forced to use RegExp and manually build the pattern:
var str = "CABC"
var str2 = "C"
var re = new RegExp(str2 + "$");
str = str.replace(re, "");
console.log(str);
You could create a regular expression from the string and preserve the dot by escaping it and use the end marker of the string to replace only the last occurence.
const
replace = (string, pattern) => string.replace(new RegExp(pattern.replace(/\./g, '\\\$&') + '$'), '')
console.log(replace(".1.2.1", ".1"));
console.log(replace("CABC", "C"));
You can check the position of the string to find using lastIndexOf and if it is at its supposed position, then just slice
function removeLastPart(str, str2)
{
result = str;
let lastIndex = str.lastIndexOf(str2);
if (lastIndex == (str.length - str2.length))
{
result = str.slice(0, lastIndex)
}
return result;
}
console.log(removeLastPart(".1.2.1", ".1"));
console.log(removeLastPart("CABC", "C"));
console.log(removeLastPart(" ispum lorem ispum ipsum", " ipsum"));
// should not be changed
console.log(removeLastPart("hello world", "hello"));
console.log(removeLastPart("rofllollmao", "lol"));
You can use String.prototype.slice
const str = "1.2.1"
const str2 = ".1";
const func = (str) => {
return str.slice(0, str.lastIndexOf("."));
}
console.log(func(str));
You could create a dynamic regex using RegExp. The $ appended will replace str2 from str ONLY if it is at the end of the string
const replaceEnd = (str, str2) => {
const regex = new RegExp(str2 + "$");
return str.replace(regex, '')
}
console.log(replaceEnd('.1.2.1', '.1'))
console.log(replaceEnd('CABC', 'C'))

How to capture variable string in replace()?

Code like this:
var v = 'd';
var re = new RegExp('a(.*?)' + v, 'gi');
"abcd".replace(re,re.$1);
I want to get "bc".
Use simply $1 in a string to get the result of the first capturing group:
var re = /a(.*)d/gi
var output = "abcd".replace(re,"$1")
console.log(output) //"bc"
You can do this easily with:
let str = "abcd";
let bc = str.replace(/a(.*)d/g,"$1");
console.log(bc) //bc
The "$1" captures whatever is in the regex () bracket.

Remove all occurrences except last?

I want to remove all occurrences of substring = . in a string except the last one.
E.G:
1.2.3.4
should become:
123.4
You can use regex with positive look ahead,
"1.2.3.4".replace(/[.](?=.*[.])/g, "");
2-liner:
function removeAllButLast(string, token) {
/* Requires STRING not contain TOKEN */
var parts = string.split(token);
return parts.slice(0,-1).join('') + token + parts.slice(-1)
}
Alternative version without the requirement on the string argument:
function removeAllButLast(string, token) {
var parts = string.split(token);
if (parts[1]===undefined)
return string;
else
return parts.slice(0,-1).join('') + token + parts.slice(-1)
}
Demo:
> removeAllButLast('a.b.c.d', '.')
"abc.d"
The following one-liner is a regular expression that takes advantage of the fact that the * character is greedy, and that replace will leave the string alone if no match is found. It works by matching [longest string including dots][dot] and leaving [rest of string], and if a match is found it strips all '.'s from it:
'a.b.c.d'.replace(/(.*)\./, x => x.replace(/\./g,'')+'.')
(If your string contains newlines, you will have to use [.\n] rather than naked .s)
You can do something like this:
var str = '1.2.3.4';
var last = str.lastIndexOf('.');
var butLast = str.substring(0, last).replace(/\./g, '');
var res = butLast + str.substring(last);
Live example:
http://jsfiddle.net/qwjaW/
You could take a positive lookahead (for keeping the last dot, if any) and replace the first coming dots.
var string = '1.2.3.4';
console.log(string.replace(/\.(?=.*\.)/g, ''));
A replaceAllButLast function is more useful than a removeAllButLast function. When you want to remove just replace with an empty string:
function replaceAllButLast(str, pOld, pNew) {
var parts = str.split(pOld)
if (parts.length === 1) return str
return parts.slice(0, -1).join(pNew) + pOld + parts.slice(-1)
}
var test = 'hello there hello there hello there'
test = replaceAllButLast(test, ' there', '')
console.log(test) // hello hello hello there
Found a much better way of doing this. Here is replaceAllButLast and appendAllButLast as they should be done. The latter does a replace whilst preserving the original match. To remove, just replace with an empty string.
var str = "hello there hello there hello there"
function replaceAllButLast(str, regex, replace) {
var reg = new RegExp(regex, 'g')
return str.replace(reg, function(match, offset, str) {
var follow = str.slice(offset);
var isLast = follow.match(reg).length == 1;
return (isLast) ? match : replace
})
}
function appendAllButLast(str, regex, append) {
var reg = new RegExp(regex, 'g')
return str.replace(reg, function(match, offset, str) {
var follow = str.slice(offset);
var isLast = follow.match(reg).length == 1;
return (isLast) ? match : match + append
})
}
var replaced = replaceAllButLast(str, / there/, ' world')
console.log(replaced)
var appended = appendAllButLast(str, / there/, ' fred')
console.log(appended)
Thanks to #leaf for these masterpieces which he gave here.
You could reverse the string, remove all occurrences of substring except the first, and reverse it again to get what you want.
function formatString() {
var arr = ('1.2.3.4').split('.');
var arrLen = arr.length-1;
var outputString = '.' + arr[arrLen];
for (var i=arr.length-2; i >= 0; i--) {
outputString = arr[i]+outputString;
}
alert(outputString);
}
See it in action here: http://jsbin.com/izebay
var s='1.2.3.4';
s=s.split('.');
s.splice(s.length-1,0,'.');
s.join('');
123.4

Categories

Resources