I need to split a string by a delimiter so that it becomes 2 arrays.
Here is an example of string "55,56,*,51,52".
I want to end up with [["55","56],["51","52"]]
I have trie with split() in javascript to no avail-
I believe I need a regex solution, which I do not know how to do.
if the string to process looks like this ",*,51,52" it should return
[[],["51,"52"]]
if it looks like "51,*," it should return [["51"],[]]
and ",*," should return [[],[]] -
Is this possible?
Thanks.
You can do this via the string.split method:
var str = "55,56,*,51,52".split('*');
for (var i=0;i<str.length;i++) str[i] = str[i].split(',');
//str now contains [["55", "56", ""], ["", "51", "52"]]
You can change your string to "55,56*51,52" to get the result of [["55","56],["51","52"]].
Alternatively, you can also do it the slightly longer way:
var str = "55,56,*,51,52".split('*');
for (var i=0;i<str.length;i++) {
str[i] = str[i].split(',');
for (var n=0;n<str[i].length;n++)
!str[i][n] && str[i].splice(n,1);
}
//str now contains [["55","56],["51","52"]]
Then it will work with the commas around the asterisk.
Here is a shorter version without using split:
function twoArrays(str) {
return JSON.parse(("[[" + str + "]]").replace(/,\*,/g, "],["));
}
// Examples:
twoArrays("55,56,*,51,52") // => [[55,56],[51,52]]
twoArrays("55,56,*,") // => [[55,56],[]]
twoArrays(",*,") // => [[],[]]
Related
I am trying to extract a string value, but I need a generic code to extract the values.
INPUT 1 : "/rack=1/shelf=1/slot=12/port=200"
INPUT 2 : "/shelf=1/slot=13/port=3"
INPUT 3 : "/shelf=1/slot=142/subslot=2/port=4"
I need the below output:
OUTPUT 1 : "/rack=1/shelf=1/slot=12"
OUTPUT 2 : "/shelf=1/slot=13"
OUTPUT 3 : "/shelf=1/slot=142"
Basically I am trying to extract up to the slot value. I tried indexOf and substr, but those are specific to individual string values. I require a generic code to extract up to slot. Is there a way how I can match the numeric after the slot and perform extraction?
We can try matching on the following regular expression, which captures all content we want to appear in the output:
^(.*\/shelf=\d+\/slot=\d+).*$
Note that this greedily captures all content up to, and including, the /shelf followed by /slot portions of the input path.
var inputs = ["/rack=1/shelf=1/slot=12/port=200", "/shelf=1/slot=13/port=3", "/shelf=1/slot=142/subslot=2/port=4"];
for (var i=0; i < inputs.length; ++i) {
var output = inputs[i].replace(/^(.*\/shelf=\d+\/slot=\d+).*$/, "$1");
console.log(inputs[i] + " => " + output);
}
You could use this function. If "subslot" is always after "slot" then you can remove the "/" in indexOf("/slot")
function exractUptoSlot(str) {
return str.substring(0,str.indexOf("/",str.indexOf("/slot")));
}
If it will always be the last substring, you could use slice:
function removeLastSubStr(str, delimiter) {
const splitStr = str.split(delimiter);
return splitStr
.slice(0, splitStr.length - 1)
.join(delimiter);
}
const str = "/rack=1/shelf=1/slot=12/port=200";
console.log(
removeLastSubStr(str, '/')
)
if you don't know where your substring is, but you know what it is you could filter it out of the split array:
function removeSubStr(str, delimiter, substr) {
const splitStr = str.split(delimiter);
return splitStr
.filter(s => !s.contains(substr))
.join(delimiter);
}
const str = "/rack=1/shelf=1/slot=12/port=200";
console.log(
removeSubStr(str, '/', 'port=200')
)
console.log(
removeSubStr(str, '/', 'port')
)
This question already has answers here:
Javascript and regex: split string and keep the separator
(11 answers)
Closed 6 years ago.
I have the following string
str = "11122+3434"
I want to split it into ["11122", "+", "3434"]. There can be following delimiters +, -, /, *
I have tried the following
strArr = str.split(/[+,-,*,/]/g)
But I get
strArr = [11122, 3434]
Delimiters are things that separate data. So the .split() method is designed to remove delimiters since delimiters are not data so they are not important at all.
In your case, the thing between two values is also data. So it's not a delimiter, it's an operator (in fact, that's what it's called in mathematics).
For this you want to parse the data instead of splitting the data. The best thing for that is therefore regexp:
var result = str.match(/(\d+)([+,-,*,/])(\d+)/);
returns an array:
["11122+3434", "11122", "+", "3434"]
So your values would be result[1], result[2] and result[3].
This should help...
str = '11122+3434+12323*56767'
strArr = str.replace(/[+,-,*,/]/g, ' $& ').split(/ /g)
console.log(strArr)
Hmm, one way is to add a space as delimiter first.
// yes,it will be better to use regex for this too
str = str.replace("+", " + ");
Then split em
strArr = str.split(" ");
and it will return your array
["11122", "+", "3434"]
in bracket +-* need escape, so
strArr = str.split(/[\+\-\*/]/g)
var str = "11122+77-3434";
function getExpression(str) {
var temp = str.split('');
var part = '';
var result = []
for (var i = 0; i < temp.length; i++) {
if (temp[i].match(/\d/) && part.match(/\d/g)) {
part += temp[i];
} else {
result.push(part);
part = temp[i]
}
if (i === temp.length - 1) { //last item
result.push(part);
part = '';
}
}
return result;
}
console.log(getExpression(str))
I have an string like'[[br,1,4,12],[f,3]]'. I want to split as strings and integers and put it into array like the string [['br',1,4,12],[f,3]].string maybe like '[]' or '[[cl,2]]',ect...but the words only,br,cl,fand i. How does get the array. Any idea for this problem?
Thanks
You can do conversion that you wanted by using RegEx :
Get your string
var str = '[[br,1,4,12],[f,3]]';
str = str.replace(/([a-zA-Z]+)/g, '"$1"');
console.log(str);
//Outputs :
[["brd",1,4,12],["f",3]] // It is still just a string
If you wanted to convert it to object, you might use this :
var str = '[[br,1,4,12],[f,3]]';
function toJSObject(str){
str = str.replace(/([a-zA-Z]+)/g, '"$1"');
return (JSON.parse(str))
}
var obj = toJSObject(str);
Coming from a PHP background, I am a little spoiled with the str_replace function which you can pass an array of haystacks & needles.
I have yet not seen such a function in Javascript, but I have managed to get the job done, altough ugly, with the below shown code:
return myString.replace(" ", "-").replace("&", ",");
However, as my need to replace certain characters with another character grows, I am sure that there's much better ways of accomplishing this - both performance-wise and prettier.
So what can I do instead?
You can use this:
var str = "How are you doing?";
var replace = new Array(" ", "[\?]", "\!", "\%", "\&");
var by = new Array("-", "", "", "", "and");
for (var i=0; i<replace.length; i++) {
str = str.replace(new RegExp(replace[i], "g"), by[i]);
}
Putting that into a function:
function str_replace(replace, by, str) {
for (var i=0; i<replace.length; i++) {
str = str.replace(new RegExp(replace[i], "g"), by[i]);
}
return str;
}
Usage example fiddle: http://jsfiddle.net/rtLKr/
Beauty of JavaScript is that you can extend the functionality of base types so you can add a method to String itself:
// v --> array of finds
// s --> array of replaces
String.prototype.replaceAll = function(v, s){
var i , ret = this;
for(i=0;i<v.length;i++)
ret = ret.replace(v[i], s[i]);
return ret;
}
and now use it:
alert("a b c d e f".replaceAll(["a", "b"], ["1", "2"])); //replaces a b with 1 2
Demo is here.
If it's easier for you, you might fancy something like this;
str.replace(/[ab]/g, function (match, i) {
switch (match) {
case "a":
return "A";
case "b":
return "B";
}
}));
i.e. make a regular expression in parameter 1 which accepts all the tokens you're looking for, and then in the function add cases to do the replacement.
Here's a mix of some of the other answers. I just like it, because of the key-value declaration of replacements
function sanitize(str, replacements) {
var find;
for( find in replacements ) {
if( !replacements.hasOwnProperty(find) ) continue;
str = str.replace(new RegExp(find, 'g'), replacements[find]);
}
return str;
}
var test = "Odds & ends";
var replacements = {
" ": "-", // replace space with dash
"&": "," // replace ampersand with comma
// add more pairs here
};
cleanStr = sanitize(str, replacements);
PHP.js has a function that could fix your issue : http://phpjs.org/functions/str_replace:527
Struggling with a regex requirement. I need to split a string into an array wherever it finds a forward slash. But not if the forward slash is preceded by an escape.
Eg, if I have this string:
hello/world
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = world
And if I have this string:
hello/wo\/rld
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = wo/rld
Any ideas?
I wouldn't use split() for this job. It's much easier to match the path components themselves, rather than the delimiters. For example:
var subject = 'hello/wo\\/rld';
var regex = /(?:[^\/\\]+|\\.)+/g;
var matched = null;
while (matched = regex.exec(subject)) {
print(matched[0]);
}
output:
hello
wo\/rld
test it at ideone.com
The following is a little long-winded but will work, and avoids the problem with IE's broken split implementation by not using a regular expression.
function splitPath(str) {
var rawParts = str.split("/"), parts = [];
for (var i = 0, len = rawParts.length, part; i < len; ++i) {
part = "";
while (rawParts[i].slice(-1) == "\\") {
part += rawParts[i++].slice(0, -1) + "/";
}
parts.push(part + rawParts[i]);
}
return parts;
}
var str = "hello/world\\/foo/bar";
alert( splitPath(str).join(",") );
Here's a way adapted from the techniques in this blog post:
var str = "Testing/one\\/two\\/three";
var result = str.replace(/(\\)?\//g, function($0, $1){
return $1 ? '/' : '[****]';
}).split('[****]');
Live example
Given:
Testing/one\/two\/three
The result is:
[0]: Testing
[1]: one/two/three
That first uses the simple "fake" lookbehind to replace / with [****] and to replace \/ with /, then splits on the [****] value. (Obviously, replace [****] with anything that won't be in the string.)
/*
If you are getting your string from an ajax response or a data base query,
that is, the string has not been interpreted by javascript,
you can match character sequences that either have no slash or have escaped slashes.
If you are defining the string in a script, escape the escapes and strip them after the match.
*/
var s='hello/wor\\/ld';
s=s.match(/(([^\/]*(\\\/)+)([^\/]*)+|([^\/]+))/g) || [s];
alert(s.join('\n'))
s.join('\n').replace(/\\/g,'')
/* returned value: (String)
hello
wor/ld
*/
Here's an example at rubular.com
For short code, you can use reverse to simulate negative lookbehind
function reverse(s){
return s.split('').reverse().join('');
}
var parts = reverse(myString).split(/[/](?!\\(?:\\\\)*(?:[^\\]|$))/g).reverse();
for (var i = parts.length; --i >= 0;) { parts[i] = reverse(parts[i]); }
but to be efficient, it's probably better to split on /[/]/ and then walk the array and rejoin elements that have an escape at the end.
Something like this may take care of it for you.
var str = "/hello/wo\\/rld/";
var split = str.replace(/^\/|\\?\/|\/$/g, function(match) {
if (match.indexOf('\\') == -1) {
return '\x00';
}
return match;
}).split('\x00');
alert(split);