Hi *John* We wish you* Happy Birthday * and blah blah blah..
Ho can I get text between each pair of * and return like
Hi <b>john</b> We wish you <b> Happy Birthday </b> and blah blah blah..
You can use this regexp /\*([^\*]+)\*/g
const regex = /\*([^\*]+)\*/g;
const str = `Hi *John* We wish you* Happy Birthday * and blah blah blah..`;
const subst = `<b>$1</b>`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
As a function
const str = `Hi *John* We wish you* Happy Birthday * and blah blah blah..`;
function bold(str) {
const regex = /\*([^\*]+)\*/g;
const subst = `<b>$1</b>`;
// The substituted value will be contained in the returned variable
return str.replace(regex, subst);
}
const result = bold(str);
console.log('Substitution result: ', result);
I think this will solve your problem.
str = "Hi *John* We wish you* Happy Birthday * and blah blah blah..";
replaceInStr(str, "<b>");
function replaceInStr(str, replace) {
str = str.replace(/\*/, replace);
if(replace === "<b>") {
replace = "</b>";
} else {
replace = "<b>";
}
if(str.search(/\*/) !== -1) {
replaceInStr(str, replace);
} else {
console.log(str);
}
}
you can use like this
var stringArray = str.split("*");
var stringOut = "";
for (var i = 0 ; i < stringArray.length; i++) {
stringOut += stringArray[i];
if (i % 2 !== 0) {
stringOut += "</br>";
}
else
{
stringOut += "<br>";
}
}
Try this :
var txt = "Hi *John* We wish you* Happy Birthday * and blah blah blah..";
txt = txt.replace(/\*(.*?)\*/g, "<b>$1</b>");
console.log(txt);
Related
I am trying to read text from PDF file using expo and React Native. I used the below code to read but it's not working. On click of a button i use the DocumentPicker to select the PDF file and then i wanted to extract the text from the document alone. I am trying to create a app to read out the text for me.
But i am not able to do that. Thanks in advance.
loadText = async()=>{
//Alert.alert("load text triggered");
let result = await DocumentPicker.getDocumentAsync({});
if(result.type == 'success') {
// alert(result.uri);
let contents = await FileSystem.readAsStringAsync(result.uri);
//console.warn('content', contents);
if(contents.length > 0){
//let res = base64.fromByteArray(this.stringToUint8Array(contents));
//alert("t" + res);
this.setState({textToBeRead : this.atob(contents)});
alert("test" + this.state.textToBeRead);
}
}
};
atob = (input) => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
let str = input.replace(/=+$/, '');
let output = '';
if (str.length % 4 == 1) {
throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (let bc = 0, bs = 0, buffer, i = 0;
buffer = str.charAt(i++);
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
buffer = chars.indexOf(buffer);
}
return output;
}
We have multiple Typewriter .tst templates in our project, and would like to share some common logic/methods between them. Is there a way to do this?
You can use T4 templates to generate the Typewriter templates. Put the code inside a reusable T4 template (*.ttinclude) and create tt-files to pass parameters to the rendering method of this base template.
(I use a Visual Studio extension for File nesting.)
Each tt-file looks something like this;
<## template debug="true" hostSpecific="true" #>
<## output extension=".tst" #>
<## include file="..\ModelsTemplate.ttinclude" #>
<# this.ModelsTemplate_Render("UserSettings"); #>
...and my ttinclude file looks like this (it is a bit project specific, but I included it all so that anyone who wants to try it out can easily get something working);
<## IntelliSenseLanguage processor="tangibleT4Editor" language="C#" #>
<#+
void ModelsTemplate_Render(string #subnamespace) {
ModelsTemplate_Render("MyApp.ViewData", #subnamespace);
}
void ModelsTemplate_Render(string #mainnamespace, string #subnamespace) {
string renderedMainNamespace = #mainnamespace;
#>
// <auto-generated>
// This code was generated by a tool.
// Template: <#= Host.TemplateFile #>
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
${
// Enable extension methods by adding using Typewriter.Extensions.*
using Typewriter.Extensions.Types;
using System.Text.RegularExpressions;
Template(Settings settings)
{
settings.IncludeProject("MyApp.ViewData");
}
static string DebugInfo = "";
string PrintDebugInfo(File f){
if (string.IsNullOrEmpty(DebugInfo)) {
return "";
}
return "/*" + Environment.NewLine + "Template debug info: " + DebugInfo + Environment.NewLine + "*/";
}
string BaseClassFullPath(Class baseClass)
{
//DebugInfo = DebugInfo + Environment.NewLine + "baseClass.FullName:" + baseClass.FullName;
var result = baseClass.Name;
// Until we find a better way to handle implementations of generic base classes...
result = result.Replace("<bool?>", "<boolean>");
result = result.Replace("<int?>", "<number>");
result = result.Replace("<long?>", "<number>");
result = result.Replace("<decimal?>", "<number>");
result = result.Replace("<double?>", "<number>");
result = result.Replace("<System.Double>", "<number>");
result = result.Replace("<System.Double?>", "<number>");
result = result.Replace("<System.DateTime?>", "<Date>");
return result;
}
string NullableFilter(string typeName)
{
return typeName.Replace("?", "");
}
string TypeFilteredPath(Type type)
{
//DebugInfo = DebugInfo + Environment.NewLine + "type:" + type.FullName + " - genericType:" + type.Unwrap().FullName;
return NullableFilter(type.Name);
}
string TypeFiltered(Type type)
{
if (type.IsEnumerable)
{
var genericType = type.Unwrap();
if (!genericType.FullName.StartsWith("System"))
{
return TypeFilteredPath(genericType)+"[]";
}
}
return TypeFilteredPath(type);
}
string PropertyTypeFiltered(Property prop)
{
return TypeFiltered(prop.Type);
}
string ImplementedInterfaces(Class c){
if (!c.Interfaces.Any()){
return string.Empty;
}
return "implements " + string.Join(", ", c.Interfaces.Select(x => x.FullName));
}
string ExtendedInterfaces(Interface i){
if (!i.Interfaces.Any()){
return string.Empty;
}
return "extends " + string.Join(", ", i.Interfaces.Select(x => x.FullName));
}
string DescriptionAttributeValue(Attribute a){
if (!a.FullName.Contains("DescriptionAttribute")){
return string.Empty;
}
return a.Value;
}
string GetPropertyDefinitionWithScope(Property p){
var definition = GetPropertyDefinition(p);
if (definition != "")
return "public " + definition;
else
return definition;
}
string GetPropertyDefinition(Property p){
var ignoreAttribute = p.Attributes.SingleOrDefault(x => x.FullName.Contains("TypeScriptIgnoreMemberAttribute"));
if (ignoreAttribute != null)
return "";
var typeAttribute = p.Attributes.SingleOrDefault(x => x.FullName.Contains("TypeScriptTypeAttribute"));
if (typeAttribute != null) {
return p.name + ": " + typeAttribute.Value + ";";
}
return p.name + ": " + TypeFiltered(p.Type) + ";";
}
string WriteImports(Class theClass){
//return "import { ViewDataEntity } from '../common/ViewDataEntity';";
var list = new List<string>();
var typesToImport = theClass.Properties.Select(x => x.Type.Unwrap()).Where(x => x.Namespace.Contains("MyApp.ViewData.")).ToList();
if (theClass.BaseClass?.Namespace.Contains("MyApp.ViewData.") == true)
typesToImport.Add(theClass.BaseClass);
foreach (var impType in typesToImport)
{
var modules = impType.Namespace.Replace("MyApp.ViewData.", "").Split('.').ToList();
string modPart = string.Join("/", modules.Select(x => CamelCase(x)));
list.Add($"import {{ {impType.Name} }} from '../{modPart}/{impType.Name}';");
}
return string.Join(Environment.NewLine, list.Distinct());
}
string CamelCase(string value){
return value.First().ToString().ToLower() + value.Substring(1);
}
}//namespace <#= renderedMainNamespace #>.<#= #subnamespace #> {
$Classes(c => c.Namespace.StartsWith("<#= #mainnamespace #>.<#= #subnamespace #>"))[
$WriteImports
export class $Name$TypeParameters $BaseClass[extends $BaseClassFullPath ] $ImplementedInterfaces {$Properties[
$GetPropertyDefinitionWithScope]
}]
$Interfaces(<#= #mainnamespace #>.<#= #subnamespace #>.*)[
export interface $Name $ExtendedInterfaces {
$Properties[
$GetPropertyDefinition]
}]
$Enums(<#= #mainnamespace #>.<#= #subnamespace #>.*)[
export class $Name {
$Values[// $Value - "$Attributes[$Value]"
static $Name = "$Name";
]
}]
$PrintDebugInfo
//}<#+
}
#>
Unfortunately there's no way to share code in tst templates. Support for this will probably come in a future version though.
I have 2 file-paths.
eg:
Path 1 C:\Users\Me\FileFolder\File1.info
Path 2 C:\Users\Me\FileFolder\DirectoryContent\Content1\File.info
I want to create a method to extract the repeated path:
Result C:\Users\Me\FileFolder
Is there a method to do this? Or how it can be done?
It can be done using String.Split method and Enumerable.TakeWhile
var part1 = path1.Split(Path.DirectorySeparatorChar);
var part2 = path2.Split(Path.DirectorySeparatorChar);
var commonParts = part1.TakeWhile((x,idx) => idx < part2.Length && part2[idx] == x);
if (commonParts.Any())
{
var result = string.Join(Path.DirectorySeparatorChar.ToString(), commonParts);
}
Fiddle
I assume you want to find all common folders, so the path that is shared from both, try this:
string path1 = #"C:\Users\Me\FileFolder\File1.info";
string path2 = #"C:\Users\Me\FileFolder\DirectoryContent\Content1\File.info";
string root1 = Path.GetPathRoot(path1);
string root2 = Path.GetPathRoot(path2);
if (root1.Equals(root2, StringComparison.InvariantCultureIgnoreCase))
{
string[] folders1 = path1.Split(Path.DirectorySeparatorChar);
string[] folders2 = path2.Split(Path.DirectorySeparatorChar);
var commonFolders = folders1.TakeWhile((dir, index) =>
folders2.Length > index &&
dir.Equals(folders2[index], StringComparison.InvariantCultureIgnoreCase));
string commonFolderPath = string.Format("{0}{1}"
, root1
, Path.Combine(commonFolders.Skip(1).ToArray())); // Skip(1) skips root
Console.Write(commonFolderPath);
}
Result: C:\Users\Me\FileFolder
Alternative way is to use Zip with TakeWhile (suggested by Selman22).
string path1 = #"C:\Users\Me\FileFolder\File1.info";
string path2 = #"C:\Users\Me\FileFolder\DirectoryContent\Content1\File.info";
string[] part1 = path1.Split(Path.DirectorySeparatorChar);
string[] part2 = path2.Split(Path.DirectorySeparatorChar);
string[] commonParts = part1.Zip(part2, (p1, p2) => p1 == p2 ? p1 : null)
.TakeWhile(s => s != null)
.ToArray();
string commonPath = string.Join(Path.DirectorySeparatorChar.ToString(), commonParts);
Slightly changed example of Selman22.
string path1 = #"C:\Users\Me\FileFolder\File1.info";
string path2 = #"C:\Users\Me\FileFolder\DirectoryContent\Content1\File.info";
string[] part1 = path1.Split(Path.DirectorySeparatorChar);
string[] part2 = path2.Split(Path.DirectorySeparatorChar);
string[] commonParts = Enumerable.Range(0, Math.Min(part1.Length, part2.Length))
.TakeWhile(i => part1[i] == part2[i])
.Select(i => part1[i])
.ToArray();
string commonPath = string.Join(Path.DirectorySeparatorChar.ToString(), commonParts);
How may I populate an array formated like this?:
var names:Array = [{label:"JAMES"}, {label:"JANE"}, {label:"JAMEL"}...];
From a XML like this one?:
<a>
<ap>
<name>JAMES</name>
<age>36</age>
</ap>
</a>
This is for AutoComplete components.
UPDATE, to start with something more suitable to my skills. THIS:
<list>
<label>ALPHA</label>
<label>ALLAN</label>
<label>ANTARES</label>
<label>...</label>
</list>
TO THIS:
var list:Array = [{label:"ALPHA"}, {label:"ALLAN"}, {label:"ANTARES"}...];
const xml:XML =
<list>
<label>ALPHA</label>
<label>ALLAN</label>
<label>ANTARES</label>
<label>...</label>
</list>;
const list:Array = new Array();
//xml..label.(trace(text()));
xml..label.(list.push({label:text()}));
// now we have an array:
// [{label:"ALPHA"}, {label:"ALLAN"}, {label:"ANTARES"}, {label:"..."}]
I recommend to read the AVM2 specification and to pay special attention to namespaces. Seriously. It's interesting and it's fun!
Hmmm... Alternative boring way:
const list:Array = new Array();
const xml:XML =
<list>
<label>ALPHA</label>
<label>ALLAN</label>
<label>ANTARES</label>
<label>...</label>
</list>;
const labels:XMLList = xml..label;
for each(var node:XML in labels)
{
trace(node);
var arrayItem:Object = new Object();
arrayItem.label = node.text(); // or node.toString() or .toJSON() or .to...
arrayItem.name = node.name();
// added only for debug-trace:
arrayItem.toString = function():String
{
var result:String = '{', delimiter:String = '';
for(var key:String in this)
if(key !== 'toString')
result += delimiter + key + ':"' + this[key] + '"',
delimiter ||= ', ';
return result + '}';
}
// add item to list:
list.push(arrayItem);
}
trace(list);
I have a JSon object like this
{
Attendance = {
Attendance = (
{
EmployeeCode = 7593;
InDate = "27/02/2013";
InTime = "08:11";
InTime2 = "00:00";
OutDate = "27/02/2013";
OutDate2 = "01/01/1901";
OutTime = "17:42";
OutTime2 = "00:00";
Present = 1;
}
);
AttendanceCount = 1;
};
AuthPersons = {
WFAuthCount = 1;
WfAuthPersons = (
{
LsAuthls = (
{
AuthEmployeeName = "SAMPLE NAME";
EmployeeCode = 4813;
}
);
RequestTypeCode = 5;
WFID = 99;
"WF_LevelID" = 2;
WorkFlowName = "EHL - Group HR (Kanchana/Asitha)";
}
);
};
}
What I wanted is to get these employeecode,IntDate... seperately So I get a seperate NSDictionary NSDictionary *summary = [resultJSON objectForKey:#"Attendance"];
and return it into my Viewcontroller method inside my Viewcontroller I have done like this.
` nsDicttendanceReqDate = [[ws GetWorkflowInfoAttendanceRequest:[NSString stringWithFormat:#"%d",usr.empCode] : #"5" :usr.stringRequestDate] copy];
dicDates= [nsDicttendanceReqDate objectForKey:#"Attendance"] ;
//dicDates=[nsDicttendanceReqDatey JSONValue];
NSLog(#"%d",[dicDates count]);
NSLog(#"DIC DATES%#",dicDates);
NSLog(#"%#",nsDicttendanceReqDate);
if ([nsDicttendanceReqDate count] > 0 ) {
NSLog(#"TESTING---------- %#",[dicDates valueForKey:#"EmployeeCode"]);
NSLog(#"TESTING---------- %#",[dicDates valueForKey:#"OutDate"] );
NSLog(#"TESTING---------- %#",[dicDates valueForKey:#"InDate"] );`
But these are getting inside paranthesis. How can I solve this.Any one can tell me how to extract this values.
Try This.It might be a help.
NSDictionary *summary = [resultJSON valueForKey:#"Attendance"]objectAtIndex:0];