Javascript Equivalent to PHP Explode() - javascript

I have this string:
0000000020C90037:TEMP:data
I need this string:
TEMP:data.
With PHP I would do this:
$str = '0000000020C90037:TEMP:data';
$arr = explode(':', $str);
$var = $arr[1].':'.$arr[2];
How do I effectively explode a string in JavaScript the way it works in PHP?

This is a direct conversion from your PHP code:
//Loading the variable
var mystr = '0000000020C90037:TEMP:data';
//Splitting it with : as the separator
var myarr = mystr.split(":");
//Then read the values from the array where 0 is the first
//Since we skipped the first element in the array, we start at 1
var myvar = myarr[1] + ":" + myarr[2];
// Show the resulting value
console.log(myvar);
// 'TEMP:data'

String.prototype.explode = function (separator, limit)
{
const array = this.split(separator);
if (limit !== undefined && array.length >= limit)
{
array.push(array.splice(limit - 1).join(separator));
}
return array;
};
Should mimic PHP's explode() function exactly.
'a'.explode('.', 2); // ['a']
'a.b'.explode('.', 2); // ['a', 'b']
'a.b.c'.explode('.', 2); // ['a', 'b.c']

You don't need to split. You can use indexOf and substr:
str = str.substr(str.indexOf(':')+1);
But the equivalent to explode would be split.

Looks like you want split

Try this:
arr = str.split (":");

create's an object :
// create a data object to store the information below.
var data = new Object();
// this could be a suffix of a url string.
var string = "?id=5&first=John&last=Doe";
// this will now loop through the string and pull out key value pairs seperated
// by the & character as a combined string, in addition it passes up the ? mark
var pairs = string.substring(string.indexOf('?')+1).split('&');
for(var key in pairs)
{
var value = pairs[key].split("=");
data[value[0]] = value[1];
}
// creates this object
var data = {"id":"5", "first":"John", "last":"Doe"};
// you can then access the data like this
data.id = "5";
data.first = "John";
data.last = "Doe";

Use String.split
"0000000020C90037:TEMP:data".split(':')

If you like php, take a look at php.JS - JavaScript explode
Or in normal JavaScript functionality:
`
var vInputString = "0000000020C90037:TEMP:data";
var vArray = vInputString.split(":");
var vRes = vArray[1] + ":" + vArray[2]; `

console.log(('0000000020C90037:TEMP:data').split(":").slice(1).join(':'))
outputs: TEMP:data
.split() will disassemble a string into parts
.join() reassembles the array back to a string
when you want the array without it's first item, use .slice(1)

With no intentions to critique John Hartsock, just in case the number of delimiters may vary for anyone using the given code, I would formally suggest to use this instead...
var mystr = '0000000020C90037:TEMP:data';
var myarr = mystr.split(":");
var arrlen = myarr.length;
var myvar = myarr[arrlen-2] + ":" + myarr[arrlen-1];

var str = '0000000020C90037:TEMP:data'; // str = "0000000020C90037:TEMP:data"
str = str.replace(/^[^:]+:/, ""); // str = "TEMP:data"

Just a little addition to psycho brmĀ“s answer (his version doesn't work in IE<=8).
This code is cross-browser compatible:
function explode (s, separator, limit)
{
var arr = s.split(separator);
if (limit) {
arr.push(arr.splice(limit-1, (arr.length-(limit-1))).join(separator));
}
return arr;
}

I used slice, split and join
You can just write one line of code
let arrys = (str.split(":").slice(1)).join(":");

So I know that this post is pretty old, but I figured I may as well add a function that has helped me over the years. Why not just remake the explode function using split as mentioned above? Well here it is:
function explode(str,begin,end)
{
t=str.split(begin);
t=t[1].split(end);
return t[0];
}
This function works well if you are trying to get the values between two values. For instance:
data='[value]insertdataherethatyouwanttoget[/value]';
If you were interested in getting the information from between the two [values] "tags", you could use the function like the following.
out=explode(data,'[value]','[/value]');
//Variable out would display the string: insertdataherethatyouwanttoget
But let's say you don't have those handy "tags" like the example above displayed. No matter.
out=explode(data,'insert','wanttoget');
//Now out would display the string: dataherethatyou
Wana see it in action? Click here.

var str = "helloword~this~is~me";
var exploded = str.splice(~);
the exploded variable will return array and you can access elements of the array be accessing it true exploded[nth] where nth is the index of the value you want to get

try like this,
ans = str.split (":");
And you can use two parts of the string like,
ans[0] and ans[1]

If you want to defined your own function, try this:
function explode (delimiter, string, limit) {
if (arguments.length < 2 ||
typeof delimiter === 'undefined' ||
typeof string === 'undefined') {
return null
}
if (delimiter === '' ||
delimiter === false ||
delimiter === null) {
return false
}
if (typeof delimiter === 'function' ||
typeof delimiter === 'object' ||
typeof string === 'function' ||
typeof string === 'object') {
return {
0: ''
}
}
if (delimiter === true) {
delimiter = '1'
}
// Here we go...
delimiter += ''
string += ''
var s = string.split(delimiter)
if (typeof limit === 'undefined') return s
// Support for limit
if (limit === 0) limit = 1
// Positive limit
if (limit > 0) {
if (limit >= s.length) {
return s
}
return s
.slice(0, limit - 1)
.concat([s.slice(limit - 1)
.join(delimiter)
])
}
// Negative limit
if (-limit >= s.length) {
return []
}
s.splice(s.length + limit)
return s
}
Taken from: http://locutus.io/php/strings/explode/

Related

Javascript Regex Custom Replace

How do I get the following conversion using Regex?
Content(input data structure):
a-test
b-123
c-qweq
d-gdfgd
e-312
Conversion:
1-test
2-123
3-qweq
4-gdfgd
Final-312
var index = 1;
function c_replace() {
if(index == 5) { return "Final"; }
return index++;
}
there you go :D
// i assume you have a string input that contains linebreaks due to your question format
const input = `a-test
b-123
c-qweq
d-gdfgd
e-312`.trim(); // removing whitespace in front or behind the input data.
//splitting the lines on whitespace using \s+
const output = input.split(/\s+/).map((s, i, a) => {
// this will map your pattern asd-foooasdasd
const data = s.match(/^[a-z]+-(.+)$/);
// you may want to tweak this. right now it will simply throw an error.
if (!data) throw new Error(`${s} at position ${i} is a malformed input`);
// figure out if we are in the final iteration
const final = i == a.length -1;
// the actual output data
return `${final ? "Final" : (i + 1)}-${data[1]}`;
// and of course join the array into a linebreak separated list similar to your input.
}).join("\n");
console.log(output);
Test
var index=1;
var text=`a-test
b-123
c-qweq
d-gdfgd
e-312`;
function c_replace() {
if(index == 5) { return "Final-"; }
return index++ +'-';
}
console.log(text.replace(/.-/g,c_replace));
var input = [
'a-test',
'b-123',
'c-qweq',
'd-gdfgd',
'e-312'
];
var output = input.map((e, i) => ++i + e.slice(1));
output[output.length - 1] = 'Final' + output[output.length - 1].slice(1);
console.log(output);

How to change a char in a string?

string[index] = 'a'
seems didn't work, it cannot change the string.
Why's that and are there any articles about this?
here an example of a function that would solve this
function replaceAt(string, index, newValue) {
if(index >= string.length || index < 0) {return false;}
var start = string.substr(0,index);
var finish = string.substr(index+1);
return start + newValue.toString() + finish;
}
Strings are not arrays but you can convert them into arrays and then join them back into strings.
var strArray = string.split("");
strArray[index] = 'a';
string = strArray.join("");

remove all empty values from url

I want to remove all empty values from an url:
var s="value1=a&value2=&value3=b&value4=c&value5=";
s = s.replace(...???...);
alert(s);
Expected output:
value1=a&value3=b&value4=c
I only need the query part of the URL to be taken into account.
Something like this:
s = s.replace(/[^=&]+=(&|$)/g,"").replace(/&$/,"");
That is, remove groups of one or more non-equals/non-ampersand characters that are followed by an equals sign and ampersand or end of string. Then remove any leftover trailing ampersand.
Demo: http://jsfiddle.net/pKHzr/
s = s.replace(/[^?=&]+=(&|$)/g,"").replace(/&$/,"");
Added a '?' to nnnnnn's answer to fix the issue where the first parameter is empty in a full URL.
This should do the trick:
var s="value1=a&value2=&value3=b&value4=c&value5=";
var tmp = s.split('&')
var newS = '';
for(var i in a) {
var t = a[i];
if(t[t.length - 1] !== '=') {
newS += t + '&';
}
}
if(newS[newS.length - 1] === '&') {
newS = newS.substr(0, newS.length - 1);
}
console.log(newS);
I don't find any solution to do that with one Regex expression.
But you could loop through your string and construct a new result string : http://jsfiddle.net/UQTY2/3/
var s="value1=a&value2=&value3=b&value4=c&value5=";
var tmpArray = s.split('&');
var final = '';
for(var i=0 ; i<tmpArray.length ; i++)
if(tmpArray[i].split('=')[1] != '')
final += tmpArray[i] + '&';
final = final.substr(0,final.length-1)
alert(final)
Where do you take all the values?
I suggest using an array:
function getValues(str){
var values = [];
var s = str.split('&');
for(var val in s){//source is a
var split = val.split('=');
if(split [1] != '' && split [1] != null){
values.push(val);
}
}
return values.join('&');
}

extracting values from string in JavaScript

Given a string of the form "(a,{b:c,d:e,f:g},h})", I want to extract a,c,e,g,h from the string.
i.e. string will always contain 3 parameters, where 2nd parameter is of the form {b:c,d:e,f:g} i.e. it contains key value pairs and there can be any number of them. I want to extract all the values leaving behind keys.
Also I want to extract first and third parameter i.e. a and h in the above string.
I am trying to scan the string and extract on character by character bases but I am not able to do extract values from 2nd argument.
Is there any efficient method to do it may be using regular expressions ?
Try this regex:
\(([a-zA-Z0-9_\-]+),\{([a-zA-Z0-9_\-]+):([a-zA-Z0-9_\-]+),([a-zA-Z0-9_\-]+):([a-zA-Z0-9_\-]+),([a-zA-Z0-9_\-]+):([a-zA-Z0-9_\-]+)\},([a-zA-Z0-9_\-]+)\}\)
The first group is a, second is b, etc:
> str.match(/\(([a-zA-Z0-9_\-]+),\{([a-zA-Z0-9_\-]+):([a-zA-Z0-9_\-]+),([a-zA-Z0-9_\-]+):([a-zA-Z0-9_\-]+),([a-zA-Z0-9_\-]+):([a-zA-Z0-9_\-]+)\},([a-zA-Z0-9_\-]+)\}\)/)
["(a,{b:c,d:e,f:g},h})", "a", "b", "c", "d", "e", "f", "g", "h"]
Here's a complicated solution using the versatile split function:
var str = "(a,{b:c,d:e,f:g},h)"
var outstr = "";
var parts = str.split(",");
for (var ixPart = 0; ixPart < parts.length; ++ixPart) {
if (ixPart > 0) outstr += ",";
var part = parts[ixPart];
if (part.indexOf(":") > 0) {
var parts2 = parts[ixPart].split(":");
var part2 = parts2[1];
if (part2.indexOf("}") >= 0)
outstr += part2.substring(0, part2.indexOf("}"));
else outstr += part2;
} else {
if (part.indexOf("(") == 0) outstr += part.substring(1);
else if (part.indexOf(")") >= 0)
outstr += part.substring(0, part.indexOf(")"));
else outstr += part;
}
}
return outstr;
How about:
var testString = "(a,{b:c,d:e,f:g},h)";
var parameterArray = testString.split(/\((.+?),\{.+?:(.+?),.+?:(.+?),.+?:(.+?)\},(.+?)\)/);
This assumes that the }) at the end of the sample string is a type-o, but it's easy to modify if not.
Divide and conquer!
function extract (str) {
str = str.trim ().split (/\s*,\s*/); // split on , chars with optional surrounding spaces
return str.map (function (v) { // create array from values
// remove prefix and/or suffix from required values :
// first ignore any leading ( or { chars
// then ignore a single word followed by :
// use the following trimmed string as the data
// ignore any ) or } at the end
return (v.match (/^[({]*(?:\w\s*:\s*)?\s*(.*?)\s*[)}]*$/) || ['', v]) [1];
});
}
This assumes that the data strings will never :
be blank
contain , characters
begin with ( or {
end with ) or }
If the format of the string is known as you described, I would first edit the string to make it into JSON and then use eval
Example:
var str1 = "('word1',{b:'word2',d:'word3',f:'word4'},'word5')";
// Edit the string to JSON format by replacing '(' and ')' with '[' and ']'
var str2 = str1.replace(/\(/, '[').replace(/\)/, ']')
// str2 is now => "['word1',{b:'word2',d:'word3',f:'word4'},'word5']"
var obj = eval(str2);
// All you results are now in obj.
var result1 = obj[0]; // This gets'word1'
//Similarly you can get the rest as follows:
obj[1].b // This gives you 'word2'
obj[1].d // 'word3'
obj[1].f // 'word4'
obj[2] // 'word5'
If obj[1] has a variable number of key/value pairs and you want only value you can iterate over the object obj[1] as follows:
for (var key in obj[1]) {
obj[1][key]; // This gives the values in each iteration
}

Matching exact string with JavaScript

How can I test if a RegEx matches a string exactly?
var r = /a/;
r.test("a"); // returns true
r.test("ba"); // returns true
testExact(r, "ba"); // should return false
testExact(r, "a"); // should return true
Either modify the pattern beforehand so that it only matches the entire string:
var r = /^a$/
or check afterward whether the pattern matched the whole string:
function matchExact(r, str) {
var match = str.match(r);
return match && str === match[0];
}
Write your regex differently:
var r = /^a$/;
r.test('a'); // true
r.test('ba'); // false
If you do not use any placeholders (as the "exactly" seems to imply), how about string comparison instead?
If you do use placeholders, ^ and $ match the beginning and the end of a string, respectively.
In case anyone receives an error like
Syntax Error: Invalid regular expression
by using the .match() function. You could always go back to the roots:
!!note this code is for matchin an exact string, if you want to search for an exact phrase in a string, you should filter it before hand
console.log("Exact data found: ", hasExactString("?hello", "?hello"))
console.log("Exact data found: ", hasExactString("?hello", "?helloBye"))
function hasExactString(data, searchTerm) {
console.log("search for ", searchTerm, " in ", data);
data = data.toLowerCase(); //if search term should be case insensitive
const searchExpressionLength = searchTerm.length;
const dataInputLength = data.length;
if (dataInputLength != searchExpressionLength) {
return false;
}
else {
//search letter by letter -back to the roots
for (var i = 0; i < searchExpressionLength; i++) {
if (data[i] != searchTerm[i]) {
return false;
}
}
return true;
}
}
...13 years late, but nonetheless^^
var data = {"values": [
{"name":0,"value":0.12791263050161572},
{"name":1,"value":0.13158780927382124}
]};
//JSON to string conversion
var a = JSON.stringify(data);
// replace all name with "x"- global matching
var t = a.replace(/name/g,"x");
// replace exactly the value rather than all values
var d = t.replace(/"value"/g, '"y"');
// String to JSON conversion
var data = JSON.parse(d);
Here's what is (IMO) by far the best solution in one line, per modern javascript standards:
const str1 = 'abc';
const str2 = 'abc';
return (str1 === str2); // true
const str1 = 'abcd';
const str2 = 'abc';
return (str1 === str2); // false
const str1 = 'abc';
const str2 = 'abcd';
return (str1 === str2); // false

Categories