add quotes mark to string - string

I want to concatenate to a string another which contains the " ' " characters
the string look as wanted But when I create an Object with this string, I'm getting a "\" inside it:
I check in https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html#//apple_ref/doc/uid/TP40014097-CH7-ID285 how to deal with special character
EDIT:
I made a mistake in understanding the source of my problem...
When I try to build a URL with URLQueryItem , there Im getting
print(EventToUrl.name) // print John's Event
let name = URLQueryItem(name: "name", value: EventToUrl.name)
print(name.description) //print name=John's Event
print(name.value) // print Optional("John\'s Event")
deepLink.queryItems = [name]
print(deepLink.url) //print Optional(https://www.example.com/?id%3D-KZXZG2bcuKHNdYNcGTF%26name%3DJohn's%2520Event%26....)
And when i try to send this deep link Im getting an error because of the " ' " characters
I also try Eric Aya's answer here :
How to use special character in NSURL?
but that not working for me:
print(EventToUrl.name) //print "John's Event"
let name = URLQueryItem(name: "name", value: EventToUrl.name.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed))
print(name.description) //Print name=John's%20Event
print(name.value) //Print Optional("John\'s%20Event")
print(deepLink.url) //print
Optional(https://www.example.com/?id%3D-KZXWVbBolmso5DT4p2I%26name%3John's%252520Event%26.......)
Self contained code :
var urlTestComponents = URLComponents()
urlTestComponents.scheme = "https"
urlTestComponents.host = "www.example.com"
urlTestComponents.path = "/"
let nameTest = URLQueryItem(name: "name", value: "John's Event")
urlTestComponents.queryItems = [name]
print(urlTestComponents.url)
The last line prints "https://www.example.com/?name=jeremie's%20Event" and If I try to send that (with whatsApp) the url is cut at the middle because of the " ' "
:

Related

Write json content in json format to a new file in Node js

Goal: To write the file content in json format using Node js. Upon opening the file manually, content should be displayed in json format
I tried both fs-extra module functions - outputJsonSync or writeFileSync to write json content to a file. They write the content inline as below
{"a":"1", "b":"2"}
However, I would like to see the content as below when I open the file manually:
{
"a" : "1",
"b" : "2"
}
I tried jsome and pretty-data on the data as follows:
fs.outputJsonSync(jsome(data))
fs.outputJsonSync(pd.json(data))
They also write data inline only with extra \ or \n and tabs added to the data but doesn't open in formatted style.
Any inputs are highly appreciated. Thanks!
[Update]
Other scenario:
const obj = {"a":"1", "b":"2"}
var string = "abc" + "splitIt" + obj
doSomething(string)
And inside the function implementation:
doSomething(string){
var arr = string.split("splitIt")
var stringToWrite = JSON.stringify(arr[1], null, ' ').replace(/: "(?:[^"]+|\\")*"$/, ' $&')
fs.writeFileSync(filePath, stringToWrite)
}
Following output is displayed when I open the file:
"[object Object]"
Once you have the object, you can specify a replacer function to separate each key-value pair by a newline, then use a regular expression to trim the leading spaces, then use another regular expression to insert a space before the : of a key-value pair. Then, just write the formatted string to a file:
const obj = {"a":"1", "b":"2"};
const stringToWrite = JSON.stringify(obj, null, ' ')
// Trim leading spaces:
.replace(/^ +/gm, '')
// Add a space after every key, before the `:`:
.replace(/: "(?:[^"]+|\\")*",?$/gm, ' $&');
console.log(stringToWrite);
Though, you may find the leading spaces more readable:
const obj = {"a":"1", "b":"2"};
const stringToWrite = JSON.stringify(obj, null, ' ')
// Add a space after every key, before the `:`:
.replace(/: "(?:[^"]+|\\")*",?$/gm, ' $&');
console.log(stringToWrite);
JSON.stringify, has two optional parameters, the first one being a replacer function, the second one(What you want) is for spacing.
const obj = {"a":"1", "b":"2"}
console.log(JSON.stringify(obj, null, 2))
This will give you:
{
"a": "1",
"b": "2"
}

Having a bot send an embed using a player command

I once again need help with creating my discord bot. I am trying to have a bot send an embed using a command. My code is too complex to send through this message because of all of the extra functions that i have in that effect the command, so I'm just going to say what the command should look like;
/embed [title]; [description]
and before the title and description would be would be
setAuthor(`${message.author.username}`, message.author.displayAvatarURL)
so the author of the embed would show up. Any idea on how to do this?
First, here is how you can use regex to parse text in a command:
case /^\/embed \[[\w ]+\]; \[[\w ]+\]$/.test(command):
sendEmbed(message);
break;
This Regular Expression (/^\/embed \[[\w ]+\]; \[[\w ]+\]$/) can be broken down as follows:
the beginning /^ and end $/ pieces mean we're trying to match an entire string / command.
/embed matches the exact text "embed"
\[[\w ]+\] is used for the title and for the description, and matches text within square brackets "[]", where the text is letters (uppercase or lowercase), numbers, underscore, or a space. If you need more characters like "!" or "-", I can show you how to add those.
.test(command) is testing that the Regular Expression matches the text from the command, and returns a boolean (true / false).
So now you put that regex checking code in your message / command listener and then call your send embed function (I named it sendEmbed) like this:
// set message listener
client.on('message', message => {
let command = message.content;
// match commands like /embed [title]; [description]
// first \w+ is for the title, 2nd is for description
if ( /^\/embed \[[\w ]+\]; \[[\w ]+\]$/.test(command) )
sendEmbed(message);
});
function sendEmbed(message) {
let command = message.content;
let channel = message.channel;
let author = message.author;
// get title string coordinates in command
let titleStart = command.indexOf('[');
let titleEnd = command.indexOf(']');
let title = command.substr(titleStart + 1, titleEnd - titleStart - 1);
// get description string coordinates in command
// -> (start after +1 so we don't count '[' or ']' twice)
let descStart = command.indexOf('[', titleStart + 1);
let descEnd = command.indexOf(']', titleEnd + 1);
let description = command.substr(descStart + 1, descEnd - descStart - 1);
// next create rich embed
let embed = new Discord.RichEmbed({
title: title,
description: description
});
// set author based of passed-in message
embed.setAuthor(author.username, author.displayAvatarURL);
// send embed to channel
channel.send(embed);
}
Let me know if you have questions!
Update Jan 2021
In the latest version of Discord js (as of Jan 2021), you'll have to create an embed like this:
const embed = new MessageEmbed()
.setTitle(title)
.setDescription(description)
.setAuthor(author.username, author.displayAvatarURL);
See example Embed in docs here. Everything else should be the same.

Swift2 - Split String to individual characters

I am trying to split a string into individual characters.
The string I want to split: let lastName = "Kocsis" so that is returns something like: ["K","o","c","s","i","s"]
So far I have tried:
var name = lastName.componentsSeparatedByString("")
This returns the original string
name = lastName.characters.split{$0 == ""}.map(String.init)
This gives me an error: Missing argument for parameter #1 in call. So basically it does't accept "" as an argument.
name = Array(lastName)
This does't work in Swift2
name = Array(arrayLiteral: lastName)
This doesn't do anything.
How should I do this? Is There a simple solution?
Yes, there is a simple solution
let lastName = "Kocsis"
let name = Array(lastName.characters)
The creation of a new array is necessary because characters returns String.CharacterView, not [String]

How to get the url part in c#?

I have a string like below.
string filePath = #"http://s.ion.com/abc/Std/isd/text.txt" or #"http://s.ion.com/abc/Std/isd/wer/we/wed/text.txt" or #"http://s.ion.com/abc/Std/isd/wer/we/wed/sa/ser/text.txt"
I need to get the output as #"http://s.ion.com/abc/Std/isd"
I have tried substring.IndxcOf method and i got isd or std alone.
Please help on this.
Original Response:
Converting the string to a Uri object, you can do the following:
//filePath = #"http://s.ion.com/abc/Std/isd/text.txt"
Uri uri = new Uri(filePath);
string output = uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last().Length - 1); // -1 removes the '/' character at the end
// output = "http://s.ion.com/abc/Std/isd"
*Note: the Last() function is from the System.Linq library. If you are not using this library, you can still obtain the last segment by replacing uri.Segments.Last().Length with uri.Segments[uri.Segments.Length - 1].Length.
Updated Response based on this comment:
//filePath = #"http://s.ion.com/abc/Std/isd/ser/wer/text.txt"
Uri uri = new Uri(filePath);
string output = uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.[uri.Segments.Length - 3].Length - 1);
// uri.Segments.Length - 3 removes the last 3 unrequired "segments"
// -1 removes the '/' character at the end
// output = "http://s.ion.com/abc/Std/isd"
Updated Response based on the last revision:
//filePath = #"http://s.ion.com/abc/Std/isd/wer/we/wed/sa/ser/text.txt"
Uri uri = new Uri(filePath);
string output = uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.[uri.Segments.Length - 6].Length - 1);
// uri.Segments.Length - 6 removes the last 6 unrequired "segments"
// -1 removes the '/' character at the end
// output = "http://s.ion.com/abc/Std/isd"
If those three strings are possible, then you can do a conditional statement to ascertain which string to manipulate.
if (/* string 1 */)
// see original response
else if (/* string 2 */)
// see first updated response
else if (/* string 3 */)
// see second updated response
string filePath = #"http://s.ion.com/abc/Std/isd/text.txt";
int index = filePath.LastIndexOf('/');
string url = filePath.Substring(0, index);
How about a regex
var url = "http://s.ion.com/abc/Std/isd/text.txt";
// or "http://s.ion.com/abc/Std/isd/wer/we/wed/text.txt"
// or "http://s.ion.com/abc/Std/isd/wer/we/wed/sa/ser/text.txt"
// or "s.ion.com/abc/Std/isd/ser/wer/text.txt"
var match = Regex.Match(url, #"^(?:http:\/\/)?(.*isd)(?=\/)");
Console.WriteLine("http://" + match.Groups[1]);
// output: http://s.ion.com/abc/Std/isd
I am not sure on the context but I always try and keep the file name and path separate for later code modification.
string filePath = #"http://s.ion.com/abc/Std/isd";
string filename = "text.txt";
You should always be able to get your path with a Path.GetDirectoryName. If you need other file names it makes the code much cleaner.

Concatenate contents of array object in jade to get a string

I have an object from which I extract values like so if I want a list:
each gear_tag in store.GearTags
li #{gear_tag.Tag.tag_name}
Now I want to concatenate all tag_names with ', ' in between. I mean that I want the resulting string to be something like:
"tag_name_1, tag_name_2, tag_name_3, tag_name_4" if the object has 4 gear_tags.
How do I achieve this?
You can use the array .map method combined with the .join method.
var tagString = store.GearTags.map(function (gear_tag) {
return gear_tag.Tag.tag_name;
}).join(', ');
Given:
store.GearTags = [
{Tag: {tag_name: 'tag_name_1'}},
{Tag: {tag_name: 'tag_name_2'}},
{Tag: {tag_name: 'tag_name_3'}}
];
The above logic would yield:
"tag_name_1, tag_name_2, tag_name_3"
Array.map iterates over every item in an array and lets you return a new value for that position in a new array that .map returns. Then Array.join does exactly what you want, returning a concatenated string of all items in the array.
With .map we create a new array with only the tag name strings in it. Then with .join we join them all together into one big comma-separated string.
Sad that I did not figure this out earlier.
- var desc_tags = ''
each gear_tag, i in store.GearTags
- if(i == retailer.GearTags.length - 1)
- desc_tags = desc_tags + gear_tag.Tag.tag_name
- else
- desc_tags = desc_tags + gear_tag.Tag.tag_name + ", "
I was typing a "- " before the "each" statement, which was causing the code not to work.
What if you do:
- var desc_tags = tags.map(function(e) {return e.Tag.tag_name}).join(', ');

Resources