React Native replace parts of string with tagged elements - ios

I have a sentence for example:
"How now brown cow"
I want to find certain words within the sentence, for example 'now' and 'cow' and have them generated with difference tags added around each word. For example:
<Text style={styles.text}>
How <TouchableHighlight><Text>now</Text></TouchableHighlight>brown<TouchableHighlight><Text>cow</Text></TouchableHighlight>
But I can't see how to add these element tags to them. The basic code is below:
render() {
return (
var sentence = "How now brown cow";
<TouchableHighlight onPress={() => this._pressRow(rowID)}>
<View>
<View style={styles.row}>
<Text style={styles.text}>
{sentence}
</Text>
</View>
</View>
</TouchableHighlight>
);
},

Split your sentence using String.prototype.split() at iterate through that array.
Make sure, that you change the flexDirection to row, otherwise the single elements will be positioned in single lines.
I added a space after each word, maybe you could look for a better solution, so that the space won't be added to the last element.
render() {
const sentence = "How now brown cow";
const words = sentence.split(' ');
const wordsToHighlight = ['now', 'cow'];
const renderWord = (word, index) => {
if(wordsToHighlight.indexOf(word) > -1) return (<TouchableHighlight><Text>{word} </Text></TouchableHighlight>);
return (<Text>{word} </Text>);
}
return (<View style={{flexDirection: 'row'}}>{React.Children.map(words, renderWord)}</View>);
}

Related

Conditional rendering of a Form.Item on Ant design

I'm trying to make a form using Ant design v4.0. The display of an Form.Item (Input text) depends of the value of other Form.Item (Radio button group). I'm using form.getFieldValue('fieldname') and it works initially but, when I changed the value of the radio Botton group the field is still showing up.
The code is similar to this
(...)
const [form] = useForm();
(...)
<Form form={form} (...)>
<Form.Item name="fieldname" initialValues={props.initialValues}>
// Here it is a radio button group
</FormItem>
{ form.getFieldValue('fieldname') === 'a_value' && (
<Form.Item name="a-text-field>
// here it is an input text
</Form.Item>
)}
</Form>
As I said before, it works with the initial value but if I changed the option it doesn't work. I also try the prop in the field a-text-field but it didn't work
hidden={form.getFieldValue('fieldname') !== 'a_value'}
it's because if the radio input changed, it does not change the form.item value so doing form.getFieldValue('fieldname') will not work. You may use a state instead and use onValuesChange prop of the form:
const [radioValue, setRadioValue] = useState("a_value");
const [form] = useForm();
(...)
const handleFormValuesChange = (changedValues) => {
const fieldName = Object.keys(changedValues)[0];
if(fieldName === "a-text-field"){
const value = changedValues[fieldName];
setRadioValue(value)
}
}
<Form form={form} onValuesChange={handleFormValuesChange}>
<Form.Item name="fieldname" initialValues={radioValue}>
// Here it is a radio button group
</FormItem>
{ radioValue === 'a_value' && (
<Form.Item name="a-text-field'>
// here it is an input text
</Form.Item>
)}
</Form>
here is the link of working sample
Check out this example in antd documentation.
https://ant.design/components/form/#components-form-demo-control-hooks
This doesn't require any state variables. The 'shouldUpdate' prop rerenders the specific form.item.

Swift - Split text based on arabic combined characters

Dears,
I have arabic sentence like this stentence
أكل الولد التفاحة
how can i split the sentence based on UNCONNECTED characters to be like this :
أ-
كل
ا-
لو-
لد
ا-
لتفا-
حة
I put - to explain what i mean.
I just need to split the text into array based on that
How can i do that using swift code for ios ?
Update:
I dont care for the spaces.
"أكل" for example is one word and doesn't contain spaces.I want to split based on UNCONNECTED characters.
So "أكل" consist from two objects : "أ" and "كل"
الولد : three objects "ا" and "لو" and "لد"
Use the below code:
let a = "أكل الولد التفاحة".split(separator: " ")
You can replace spaces with "-" using replacing occurences function.
let text = "أكل الولد التفاحة".replacingOccurrences(of: " ", with: "-", options: NSString.CompareOptions.literal, range: nil) ?? ""
I don't know how accepted answer helps to fix the issue.
Apple already provided Natural Language Framework to handle such a things which more trustworthy
When you work with natural language text, it’s often useful to tokenize the text into individual words. Using NLTokenizer to enumerate words, rather than simply splitting components by whitespace, ensures correct behavior in multiple scripts and languages. For example, neither Chinese nor Japanese uses spaces to delimit words.
Here is example
let text = """
All human beings are born free and equal in dignity and rights.
They are endowed with reason and conscience and should act towards one another in a spirit of brotherhood.
"""
let tokenizer = NLTokenizer(unit: .word)
tokenizer.string = text
tokenizer.enumerateTokens(in: text.startIndex..<text.endIndex) { tokenRange, _ in
print(text[tokenRange])
return true
}
Here is link of Apple docs
Hope it is helpful
There is two box you can just click in first. Content automatically paste click convert. Output data automatically copied with spaces I used for this quran
<h1>Allah</h1>
<center>
<textarea id="field" onclick="paste(this)" style="font-size: xxx-large;min-width: 90%; min-height: 200px;"> </textarea>
<center>
</center>
</br>
<textarea id="field2" style="font-size: xxx-large;min-width: 95%; min-height: 200px;"> </textarea>
</center>
<center>
<br>
<button onclick="myFunction()" style="font-size: xx-large;min-width: 20%;">Convert</button>
</center>
<script >
function myFunction(){
var string = document.getElementById("field").value;
// Option 1
string.split('');
// Option 2
console.log(string);
// Option 3
Array.from(string);
// Option 4
var bb = Object.assign([], string);
console.log(bb);
cleanArray = bb.filter(function () { return true });
var filtered = bb.filter(function (el) {
return el != null; });
console.log(filtered);
var bb = bb.toString();
console.log(bb);
bb = bb.replace(",","");
var stringWithoutCommas = bb.replace(/,/g, ' ');
console.log(stringWithoutCommas);
document.execCommand(stringWithoutCommas)
document.getElementById("field2").value = stringWithoutCommas;
var copyTextarea = document.querySelector('#field2');
copyTextarea.focus();
copyTextarea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
};
/*
var copyTextareaBtn = document.querySelector('#newr');
copyTextareaBtn.addEventListener('click', function(event) {
var copyTextarea = document.querySelector('#field2');
copyTextarea.focus();
copyTextarea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
});
*/
async function paste(input) {
document.getElementById("field2").value = "";
const text = await navigator.clipboard.readText();
input.value = text;
}
</script>
Try this:
"أكل الولد التفاحة".map {String($0)}

How parse the text between the element of xml file in python

I want to parse the xml file as following
<book attr='1'>
<page number='1'>
<text> sss </text>
<text> <b>bb<i>sss<b></i></b></text>
<text> <i><b>sss</b></i></text>
<text><a herf='a'> sss</a></text>
</page>
<page number='2'>
<text> sss2 </text>
<text> <b>bb<i>sss2</i><b></text>
<text> <i><b>sss2</b></i></text>
<text><a herf='a'> sss2</a></text>
</page>
.......
</book>
I want to extract all the text between the 'text' element. But there are 'b' 'i' 'a' elements et al., in between the 'text' element.
I have tried to use the following code.
tree = ET.parse('book.xml')
root = tree.getroot()
for p in root.findall('page'):
print(p.get('number'))
for t in p.findall('text'):
print(t.text)
But the result:
1
sss
None
None
None
2
sss2
None
None
None
Actually, I want to extract all the text between the and , and join to be sentence like the following:
1
bb sss
sss
sss
sss
2
bb sss2
sss2
sss2
sss2
But how to parse the subelement between the 'text' thanks!
For parsing XML you can use BeautifulSoup. The text between elements can be obtained with get_text() method:
data = '''<book attr='1'>
<page number='1'>
<text> sss </text>
<text> <b>bb<i>sss<b></i></b></text>
<text> <i><b>sss</b></i></text>
<text><a herf='a'> sss</a></text>
</page>
<page number='2'>
<text> sss2 </text>
<text> <b>bb<i>sss2</i><b></text>
<text> <i><b>sss2</b></i></text>
<text><a herf='a'> sss2</a></text>
</page>'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(data, 'lxml')
for page in soup.select('page[number]'):
print(page['number'])
for text in page.select('text'):
print(text.get_text(strip=True, separator=' '))
Prints:
1
sss
bb sss
sss
sss
2
sss2
bb sss2
sss2
sss2

Pulling out lines which contain certain words exactly once

I am trying to pull out lines in a tab delimited text file which contain all user-specified words exactly once (the sequence doesn't matter).
For example, I need to find lines which contain 'CA_', 'CS_', 'XV_' and 'JS_' exactly once.
Can I use grep for that?
Here is a possible solution. Is that what you are trying to do?
var rawString = 'CA_1234567 CA_R345335 CS_I8788765 CA_3456783 CS_0986887 CS_scaffolding2 CA_scaffolding3';
var valArr = rawString.split(' ');
//note: in real code, put CA, CA etc in an array and iterate
var CAItems = $.grep(valArr, function(val)
{
if (val.startsWith('CA'))
{
return val;
}
});
var CSItems = $.grep(valArr, function(val)
{
if (val.startsWith('CS'))
{
return val;
}
});
$('#CAValuesTxt').text(CAItems.join(' '))
$('#CSValuesTxt').text(CSItems.join(' '))
String.prototype.startsWith = function (prefix) {
return this.indexOf(prefix) === 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>Values starting with CA: </label>
<label id='CAValuesTxt'></label>
<br/>
<br/>
<label>Values starting with CS: </label>
<label id='CSValuesTxt'></label>
I hope it helps!

TinyMCE Paragraph Text Only but with some buttons like bold, italics

For my website I need the input passed from TinyMCE to be 1 specific font.
I need them to be able to insert links, make text bold, underlined or italics. They get to have 2 headers to chose from, Header 2 and Header 3 and paragraph.
Now the problem is, I can't make the editor paste as text. If I open word I can copy and paste text with font, lets say, Chiller and it shows up as chiller.
How can I make all copy/pasted text show as my desired font (paragraph format) while allowing some buttons to work such as bold..etc.
What I currently have:
<script type="text/javascript">
tinyMCE.init({
mode : "textareas",
theme : "advanced",
editor_selector : "body_content",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align: "left",
theme_advanced_buttons1: "bold,italic,underline,hr,strikethrough,formatselect,separator,undo,redo",
theme_advanced_buttons2: "justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,separator,link,unlink",
theme_advanced_buttons3: "",
theme_advanced_blockformats: "p,h2,h3",
extended_valid_elements: "iframe[title|width|height|src]",
theme_advanced_fonts : "Arial=arial",
plugins : "wordcount",
setup : function(ed){
ed.onKeyUp.add(function(ed){
///
var r = 0;
var y = tinyMCE.get('body_content').getContent();
var n = "<?php echo $max;?>";
y = y.replace(/\s/g,' ');
y = y.split(' ');
for (i=0; i<y.length; i++)
{
if (y[i].length > 0) r++;
}
var word_remain=n-r;
if(word_remain<0)
word_remain=0;
jQuery('#body_word_remain').html(word_remain);
var keypressed = null;
if (window.event)
{
keypressed = window.event.keyCode;
}
else
{
keypressed = ed.which; //NON-IE, Standard
}
if (r > n )
{
var prescribed = "<?php _e('You have exceeded the prescribed ','ad')?>";
prescribed += (r-n);
prescribed += "<?php _e(' word(s)','ad');?>";
jQuery('#prescribed').html(prescribed);
}
else
{
jQuery('#prescribed').html('');
}
});
}
});
</script>
The example here works the way I want it to:
http://fiddle.tinymce.com/
But I am not sure what they have used to achieve that effect. I am using a version 3.9.3 released on 2010-12-20 and I'd rather not update it if possible. But if I do need to update it to get my desired effect I will.
Thank you! Any help is appreciated.

Resources