add/remove text multiple line for javascript - javascript

I have the multiple line string which need to remove/add
here's the data that I would like to edit
data{
id
date
***progress{
update
progressStatus
}***
events {
id
time
}
}
my point is how do I remove
progress{
update
progressStatus
}
I had tried 'replace', 'assign' to remove it as below but not working
const test = data.replace(progress, '');
Thank you.

Here's the logic, I'm considering that you want to remove the "progress" which has an open curly bracket('{') and a closing curly bracket('}'):
var data = `data{
id
date
***progress{
update
progressStatus
}***
events {
id
time
}
}`;
function _remove(data, key) {
var s = data.indexOf(key);
var e = ((s) => {
for(var i=s; i<data.length; i++){
if(data[i] == "}")
return i;
}
})(s + key.length);
console.log(data.replace(data.substr(s, e-s+1), ""));
}
_remove(data, 'progress');
Can be done with regex as well!

What is I have the multiple line ? The query of grapqh will return an object, why still a multiple string ?
In your case (the query data is a string), try:
const data = ` data{
id
date
progress{
update
progressStatus
}
events {
id
time
}
}`
const newData = data.replace(`progress{
update
progressStatus
}`, '')
console.log(newData)
If you want to delete one key in object, try this:
delete data.progress;
// or,
delete data['progress'];
// or,
const prop = "progress";
delete data[prop];
Demo:
const data = {
progress: {
x: "x"
},
events: {
id: 1
}
}
delete data.progress
console.log(data)

You could try with a regexep
const regex = /progress{[^}]+}\s+/gm;
const str = `data{
id
date
progress{
update
progressStatus
}
events {
id
time
}
}`;
const subst = ``;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);

Related

Get payload from String

I have this String:
['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
I want to get the keys 'TEST1-560' which is always fist and "car" value.
Do you know how I can implement this?
This is a very, very scuffed code, but it should work for your purpose if you have a string and you want to go through it. This can definitely be shortened and optimized, but assuming you have the same structure it will be fine.:
// Your data
var z = `['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']`;
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1,dividedVar[ind].split(":")[1].split("}")[0].length-1);
console.log(car)
}
}
console.log(testName);
output:
BLUE
TEST1-560
In a real application, you don't need to log the results, you can simply use the variables testName,car. You can also put this in a function if you want to handle many data, e.g.:
function parseData(z) {
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1, dividedVar[ind].split(":")[1].split("}")[0].length - 1);
}
}
return [testName, car]
}
This will return the variables values in an array you can use
const arr = ['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
const testValue = arr[0];
const carValue = JSON.parse(arr[1]).data[0].car;
console.log(testValue);
console.log('-----------');
console.log(carValue);
If your structure is always the same, your data can be extracted like above.

Why does findIndex() return 0, instead of the desired index?

I've been stuck trying to figure out how to retrieve a desired index. I have a user adding names to a Guestlist, with the option to remove names. All the names are appended to an array saved to localStorage. When the delete button is clicked, I want to iterate over the array, find the matching string and retrieve it's index. All I'm getting however, is a -1 if the string doesn't match, and 0 if it matches. Where is my error? Any help is appreciated.
deleteBtn.addEventListener('click', function () { // Makes the Delete button active.
const deleteName = this.parentElement.innerText; // parent element is li
const test = localStorage.getItem('data');
const testParsed = JSON.parse(test);
for (let i = 0; i < testParsed.length; i++) {
let compare = `Name: ${testParsed[i].name}, About: ${testParsed[i].about}Delete entry`; // matches innerHtml of deleteName
compare.replace('.,:', ''); // Removes unwanted punctuation
console.log('Compare: ', compare);
function index(){
return deleteName === compare;
}
console.log(testParsed.findIndex(index));
I played around some more, and figured it out. I'll leave the question up in case someone else can make use of it.
deleteBtn.addEventListener('click', function () { // Makes the Delete button active.
const deleteName = this.parentElement.innerText; // parent element is li
const test = localStorage.getItem('data');
const testParsed = JSON.parse(test);
console.log(test);
for (let i = 0; i < testParsed.length; i++) {
let compare = `Name: ${testParsed[i].name}, About: ${testParsed[i].about}Delete entry`; // matches innerHtml of deleteName
compare.replace('.,:', ''); // Removes unwanted punctuation
console.log('Compare: ', compare);
if(deleteName === compare) {
function index(equals) { // compare is string, equals is object
return equals.name === testParsed[i].name && equals.about === testParsed[i].about;
}
console.log(testParsed.findIndex(index));
}

Parse ajax response object data

I'm passing an object using the jQuery $.post method. When it's loaded using the $.get method, I need that the message field of the object is parsed correctly. I was able to remove the equal "=" sign and the "&" sign, but if it's a long message it will contain the plus "+" sign and the commas are not displayed correctly. Here is the console output i get:
{user: "demo", message: "Lorem+ipsum+dolor+sit+amet%2C+consectetur+adipisci…+qui+officia+deserunt+mollit+anim+id+est+laborum."}
message: "Lorem+ipsum+dolor+sit+amet%2C+consectetur+adipiscing+elit%2C+sed+do+eiusmod+tempor+incididunt+ut+labore+et+dolore+magna+aliqua.+Ut+enim+ad+minim+veniam%2C+quis+nostrud+exercitation+ullamco+laboris+nisi+ut+aliquip+ex+ea+commodo+consequat.+Duis+aute+irure+dolor+in+reprehenderit+in+voluptate+velit+esse+cillum+dolore+eu+fugiat+nulla+pariatur.+Excepteur+sint+occaecat+cupidatat+non+proident%2C+sunt+in+culpa+qui+officia+deserunt+mollit+anim+id+est+laborum."
user: "demo"
__proto__: Object
The commas are replaced by the %2C character and the spaces are replaced from the plus sign.
How to obtain the text without this signs?
here is a function I write for this scope, but it's not working at all.
function parseData(data){
var params = {}
params.data = data.split("&");
params.result = {};
for(var i = 0; i < params.data.length; i++) {
var item = params.data[i].split("=");
params.result[item[0]] = item[1];
}
return params.result;
}
Use this one :
function parseData(data){
return decodeURIComponent((data + '').replace(/\+/g, '%20'));
}
Use this function hope it will work for you :
export function parseData(data) {
url = decodeURI(url);
if (typeof url === 'string') {
let params = url.split('?');
let eachParamsArr = params[1].split('&');
let obj = {};
if (eachParamsArr && eachParamsArr.length) {
eachParamsArr.map(param => {
let keyValuePair = param.split('=')
let key = keyValuePair[0];
let value = keyValuePair[1];
obj[key] = value;
})
}
return obj;
}
}

How to remove "Fruit" value from my text input area

So i need to remove the value that i added at the text input area as a chip, but i dont know how to solve the codes to link the it together and remove it. So what should happen is when the proper codes are linked together, it should be able to be removed when i click the "x" on the chip.
i'm able to add the values, but when i click remove the values are still there.
add(event: MatChipInputEvent): void {
const input = event.input;
const value = event.value;
console.log(`mat chip`, event);
console.log(`mat chip value`, value);
// Add our fruit
if ((value || '').trim()) {
this.fruits.push({name: value.trim()});
console.log(`fruits`, this.fruits);
let type = this.editDeliveryOrderForm.value.type;
type += ',' + value.trim();
this.editDeliveryOrderForm.patchValue({
type
});
}
// Reset the input value
if (input) {
input.value = '';
}
}
remove(fruit: Fruit): void {
const index = this.fruits.indexOf(fruit);
const value = fruit.name;
// console.log(`mat chip`, event);
// console.log(`mat chip value`, value);
if (index >= 0) {
this.fruits.splice(index, 1);
// this.fruits.push({name: value.trim()});
// console.log(`fruits`, this.fruits);
let type = this.editDeliveryOrderForm.value.type;
value.trim();
this.editDeliveryOrderForm.patchValue({
type
});
}
Array method indexOf() is case sensitive. The object which passed to fruits array does not return the index.
const index = this.fruits.indexOf(fruit);
//console.log(index);
if(index !== -1) {
// code..
}
You can use Array.filter() to filter the elements in array
remove(fruit: Fruit): void {
this.fruits = this.fruits.filter((fr)=>fr.name !== fruit.name);
}
This will return new array removing the current fruit.

Matching a string to an array

I need your your help,
For some strange reason, when my var str is set to "OTHER-REQUEST-ASFA" the matched key comes back as "ASF" as opposed to "ASFA"
How can I get the returned output key of "ASFA" when my str is "OTHER-REQUEST-ASFA"
function test() {
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
for (var key in filenames) {
if (str.indexOf(key) != -1) { alert(filenames[key]) }
}
}
You could switch from
str.indexOf(key)
to
key.indexOf(str)
function test() {
var str = "OTHER-REQUEST-ASFA",
filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
},
key;
for (key in filenames) {
if (key.indexOf(str) != -1) {
console.log(filenames[key]);
}
}
}
test();
To answer why it's not working as you want...
You've got:
str.indexOf(key)
This checks for the first instance of key in str.
So in your loop, key first equals OTHER-REQUEST-ASF which is part of OTHER-REQUEST-ASFA, so the condition is true.
However, to do what you want to do, if you know the pattern is always going to be OTHER-REQUEST-XYZ, the easiest way is to use split():
str.split('-')[2]
will always return the last section after the last -
cause "OTHER-REQUEST-ASFA".indexOf("OTHER-REQUEST-ASF") will not return -1, so it will show "ASF"
You can also use static method Object.keys() to abtain array of keys
var test = () =>{
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
Object.keys(filenames).forEach(x => {
if ( x.indexOf(str) !== -1)
console.log(filenames[str]);
});
}
test();

Categories