How to get specific text from a string using javascript - javascript

I am trying to get text from an array except year,month,date using javascript.I do not know how do it.
var arr = [
"power-still-rate-19.08.22",
"main-still-rate-19.08.22",
"oil-power-rate-19.08.22",
"oil-mill-rate-19.7.2"
];
var result;
for (var i = 0; i < arr.length; i++) {
result = arr[i].remove('?????????');
}
console.log(result);
//result should be like = power-still-rate,main-still-rate,oil-power-rate ;

Split, slice and join
var arr = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"];
var result = arr.map(item => item.split("-").slice(0,-1).join("-"))
console.log(result);
Split, pop and join
var arr = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"];
var result = arr.map(item => { let res = item.split("-"); res.pop(); return res.join("-") })
console.log(result);
No map:
var arr = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"];
var result = arr.join("").split(/-\d{1,}\.\d{1,}\.\d{1,}/);
result.pop(); // last empty item, not needed if you do not want an array just join with comma
console.log(result);

Use a regular expression to match non-digit characters from the start of the string, followed by - and a digit:
const input = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"];
const output = input.map(str => str.match(/\D+(?=-\d)/)[0]);
console.log(output);

Using split on - ,splicing the last element which is the date and joining on -
var arr=["power-still-rate-19.08.22","main-still-rate-19.08.22","oil-power-rate-19.08.22"];
arr.forEach(function(e,i){
arr[i]=e.split('-').splice(0,3).join('-')
})
console.log(arr)

You can remove back string by using slice function and join them with join function.
var arr = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"];
var result = arr.map(str => str.slice(0, str.lastIndexOf('-'))).join(',');
console.log(result);

You can use String#replace method to remove certain pattern from string using RegExp.
const input = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"];
const res = input.map(str => str.replace(/-\d{1,2}\.\d{1,2}\.\d{1,2}$/, ''));
console.log(res);

Related

How to extract specific words from a string with some patterns?

I am trying to extract some strings from a word with some pattern like -
"38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"
how will I extract all word between - separately, means first word before - and then second word between - and - and so on...
string = "38384-1-page1-2222";
string.substr(0, string.indexof("-")); //return 38384
But how will I extract 1, page1 and 2222 all the words separately?
The javascript function str.split(separator) split the string by the given separator and it returns an array of all the splited string. REF Here
Here is an example following your question :
var string = "38384-1-page1-2222";
var separator = "-";
var separated = string.split(separator);
var firstString = separated[0]; // will be '38384'
var secondString = separated[1]; // will be '1'
var thirdString = separated[2]; // will be 'page1'
/* And So on ... */
Hope this can help
Use String.prototype.split() to get your string into array
var words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
var resultArray = [];
for (let i = 0; i < words.length;i++) {
let temp = words[i];
resultArray = pushArray(temp.split("-"), resultArray)
}
console.log(resultArray)
function pushArray (inputArray, output) {
for (let i = 0; i < inputArray.length;i++) {
output.push(inputArray[i]);
}
return output;
}
Or simply use Array.prototype.reduce()
var words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
var result = words.reduce((previousValue, currentValue) => previousValue.concat(currentValue.split("-")), [])
console.log(result)
You can use regex /[^-]+/g
const words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
console.log(words.map(v=>v.match(/[^-]+/g)).flat())

Convert a string to array format java script

I hava a string like this "sum 123,645,423,123,432";
How can i convert this string to be like this:
{
“sum”: [ 123,645,423,123,432 ]
}
I try it like this:
var arr = "sum 123,645,423,123,432";
var c = arr.split(',');
console.log(c);
VM3060:1 (5) ["sum 123", "645", "423", "123", "432"]
Thanks!
First, i .split() the string by whitespace, that returns me an array like this ["sum" , "123,645,423,123,432"]
Instead of writing var name = str.split(" ")[0] and var arrString = str.split(" ")[1] i used an destructuring assignment
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Next step is to split the arrString up by , and then .map() over each element and convert it to an number with Number().
Finally i assign an object to result with a dynamic key [name] and set arr to the dynamic property.
var str = "sum 123,645,423,123,432";
var [name,arrString] = str.split(" ");
var arr = arrString.split(",").map(Number);
let result = {
[name]: arr
}
console.log(result);
//reverse
var [keyname] = Object.keys(result);
var strngArr = arr.join(",");
var str = `${keyname} ${strngArr}`
console.log(str);
const str = "sum 123,645,423,123,432";
const splittedString = str.split(" ");
const key = splittedString[0];
const values = splittedString[1].split(",").map(Number);
const myObject = {
[key]: [...values]
};
console.log(myObject);
There are many ways to dot that,one way to do it using String.prototype.split()
let str = "sum 123,645,423,123,432";
let split_str = str.split(' ');
let expected = {};
expected[split_str[0]] = split_str[1].split(',');
console.log(expected);
This solution is equivalent to #Yohan Dahmani with the use of destructuring array for more legible code.
const str = "sum 123,645,423,123,432";
const [key,numbersStr] = str.split(' ');
const numbersArr = numbersStr.split(',').map(n => parseInt(n, 10));
const result = {[key]: numbersArr};
console.log(result);

How to split a string into an array at a given character (Javascript)

var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
//Finished result should be:
result == ["10000.", "9409.", "13924.", "11025.", "10000.", "_.", "11025.", "13225.", "_.", "9801.", "12321.", "12321.", "11664."]
After each "." I want to split it and push it into an array.
You split it, and map over. With every iteration you add an . to the end
var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
let result = stringToSplit.split(".").map(el => el + ".");
console.log(result)
You could match the parts, instead of using split.
var string = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.",
result = string.match(/[^.]+\./g);
console.log(result);
var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
var arr = stringToSplit.split(".").map(item => item+".");
console.log(arr);
split the string using . delimiter and then slice to remove the last empty space. Then use map to return the required array of elements
var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
let newData = stringToSplit.split('.');
let val = newData.slice(0, newData.length - 1).map(item => `${item}.`)
console.log(val)
you could use a lookbehind with .split
var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
let out = stringToSplit.split(/(?<=\.)/);
console.log(out)

Extracting Key:Value pairs assoc with regex from string on Javascript

I have the following string
server:all, nit:4545, search:dql has map
with the regular expression /(\w+):((?:"[^"]*"|[^:,])*)/g I get
["server:all", "nit:4545", "search:dql has map"] //Array
But I want to get
{server:"all","nit":"4545","search":"dql has map"}
OR
[{server:"all"},{"nit":"4545"},{"search":"dql has map"}]
You can use a simple regex for key:value and use a look using exec:
var str = 'server:all, nit:4545, search:dql has map';
var re = /([\w-]+):([^,]+)/g;
var m;
var map = {};
while ((m = re.exec(str)) != null) {
map[m[1]] = m[2];
}
console.log(map);
You can use String#replace to loop over the matches and captures and assign those to an empty object.
const string = 'server:all, nit:4545, search:dql has map';
const regex = /(\w+):((?:"[^"]*"|[^:,])*)/g;
const map = {};
string.replace(regex, (m, c1, c2) => {
map[c1] = c2;
});
console.log(map);
For your example data, you could also first split on a comma and then split on a colon:
let str = "server:all, nit:4545, search:dql has map";
let result = {};
str.split(',').forEach(function(elm) {
[k, v] = elm.trim().split(':');
result[k] = v;
});
console.log(result);

Remove duplicate in a string - javascript

I have a string in javascript where there are a lot of duplicates. For example I have:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
What can I do to delete duplicates and to get for example x="Int32,Double"?
With Set and Array.from this is pretty easy:
Array.from(new Set(x.split(','))).toString()
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
x = Array.from(new Set(x.split(','))).toString();
document.write(x);
If you have to support current browsers, you can split the array and then filter it
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
var arr = x.split(',');
x = arr.filter(function(value, index, self) {
return self.indexOf(value) === index;
}).join(',');
document.body.innerHTML = x;
Use new js syntax remove Dupicate from a string.
String.prototype.removeDuplicate = Function() {
const set = new Set(this.split(','))
return [...set].join(',')
}
x.removeDuplicate()
function myFunction(str) {
var result = "";
var freq = {};
for(i=0;i<str.length;i++){
let char = str[i];
if(freq[char]) {
freq[char]++;
} else {
freq[char] =1
result = result+char;
}
}
return result;
}
That is a more readable and better parameterized solution:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
var removeDup = [...new Set(x.split(","))].join(",");
//result "Int32,Double"
Check This out -
removeDuplicates() function takes a string as an argument and then the string split function which is an inbuilt function splits it into an array of single characters. Then the arr2 array which is empty at beginning, a forEach loop checks for every element in the arr2 - if the arr2 has the element it will not push the character in it, otherwise it will push. So the final array returned is with unique elements. Finally we join the array with the join() method to make it a string.
const removeDuplicates = (str) => {
const arr = str.split("");
const arr2 = [];
arr.forEach((el, i) => {
if (!arr2.includes(el)) {
arr2.push(el);
}
});
return arr2.join("").replace(",", "").replace("", " ");
};
console.log(removeDuplicates( "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"));
Its simple just remove duplicates in string using new Set and join them.
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
console.log([...new Set(x)].join(""));
function removeDups(s) {
let charArray = s.split("");
for (let i = 0; i < charArray.length; i++) {
for (let j = i + 1; j < charArray.length; j++)
if (charArray[i] == charArray[j]) {
charArray.splice(j, 1);
j--;
}
}
return charArray.join("");
}
console.log(removeDups("Int32,Int32,Int32,InInt32,Int32,Double,Double,Double"));
You can use Set()
const result = Array.from(new Set(x)).join('')
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
const result = Array.from(new Set(x)).join('')
console.log(result)
you can use the replaceAll function:
let str = "/Courses/"
let newStr = str.replaceAll('/', '')
console.log(newStr) // result -> Courses
function removeDuplicate(x)
{
var a = x.split(',');
var x2 = [];
for (var i in a)
if(x2.indexOf(a[i]) == -1) x2.push(a[i])
return x2.join(',');
}
const str = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
const usingSpread = [...str]
const duplicatesRemove = [...new Set(usingSpread)]
const string = duplicatesRemove.join("")
console.log("After removing duplicates: " + string)
STEPS
convert string to character array using spread operator
new Set will implicitly remove duplicate character
convert character array to string using join("") method

Categories

Resources