How to substring method in React native? I tried all methods which are given below but none of the method worked.
substring, slice, substr
The substring method is applied to a string object.
The substring() method extracts the characters from a string, between two specified indices, and returns the new substring.
This method extracts the characters in a string between "start" and "end", not including "end" itself.
If "start" is greater than "end", this method will swap the two arguments, meaning str.substring(1, 4) == str.substring(4, 1).
If either "start" or "end" is less than 0, it is treated as if it were 0.
Note: The substring() method does not change the original string.
The way to use it is this:
var str = "Hello world!";
var res = str.substring(1, 4);
// res value is "ell"
https://www.w3schools.com/jsref/jsref_substring.asp
You can use it :
var str = "Hello world!";
var res = str.substring(0, 4); // output is Hello
if you get from JSON
{item.name.substring(0, 4)}
from text
this is text.substring(0, 5) // output is: this i
Method 1: With Variables
var str = "Demo String";
var res = str.substring(2, 5); //starts from 0
Method 2: With States Directly
<Text>{this.state.str.substring(0, 7)}</Text>
try
(obj.str).substring(1, 4);
Another alternative, you can make simple function. and then print in your jsx.
var number = "62857123456"
const slice = {
phone: (input: string = '') => {
let output = '';
// you can use substring, slice, substr
output = input.slice(2,14);
return output;
},
};
Finally, print on your jsx by calling the function that was created.
{slice.phone(number)}
I have faced the same situation For this the solution is place all js code in a function and call it externally
class AboutMe extends Component {
displayAboutMe(){
var data = this.props.getAboutMeQuery;
if(data.loading){
return(<div>Loading Books</div>)
}else{
var aboutMe = JSON.stringify(this.props.getAboutMeQuery.aboutme);
console.log(aboutMe);
var res = aboutMe.substring(12,453);
console.log(res);
}
}
render(){
this.displayAboutMe()
return (
<div id="profile-section"></div>
)}}
Related
I am trying to execute an SQL statement at AWS QLDB like the example in the AWS SDK Git but using Kotlin. The example shows me that I can return something at "execute" (represented by "searchValue")
String searchValue = driver.execute(
txn -> {
Result result = txn.execute(searchQuery);
String value = "";
for (IonValue row : result) {
value = ((IonString) row).stringValue();
}
return value;
});
Based on the example, I've tried to receive the return in "executionReturn" and transform the values at "let" function but "executionReturn" cames as undefined.
val executionReturn = driver.execute { txn: TransactionExecutor ->
val result: Result = txn.execute(
"SELECT * FROM Table")
)
result
}
executionReturn.let {
list.plus(it as IonStruct)
}
How could I return a specific value from "driver.execute"?
Thanks for your interest in QLDB. Does something like the following help you?
val executionReturn = driver.execute<List<IonValue>> { txn: TransactionExecutor ->
val result = txn.execute(
"SELECT * FROM Table").toList()
result
}
executionReturn.let {
list.plus(it as IonStruct)
}
I've changed the approach of the collection. I've created a mutableListOf and then used the method "add"
Then it worked
this is the problem
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
myCode
class Solution {
fun isPalindrome(s:String):Boolean {
var s1 = s.toLowerCase()
var myStringBuilder = StringBuilder()
var n = s1.length-1
var n1=myStringBuilder.length
for ( i in 0..n) {
if (Character.isLetterOrDigit(s1[i])) {
myStringBuilder.append(s1[i])
}
}
for( i in 0 .. (n1/2)-1){
if(myStringBuilder[i] != myStringBuilder[n1-i-1]){
return false
}
}
return true
}
}
the first case passed
but this is not passed as per the result Input: s = "race a car result true expected is false
You're initialising n1 too early:
// create an -empty- StringBuilder
var myStringBuilder = StringBuilder()
...
// since it's empty, n1 == 0
var n1=myStringBuilder.length
You're setting it to the length of the StringBuilder contents before you've actually put anything in it. This is a simple value you're setting, it's not a reference to the length getter that will give the current value when you access it. You set it once and that's its value forever.
So your last loop, the one that checks if it's a palindrome or not, never actually runs:
// since n1 is 0, this is for (i in 0..0)
for( i in 0 .. (n1/2)-1){
You can fix it by initialising n1 when you've finished adding your content to the StringBuilder, so you can get its final length:
for ( i in 0..n) {
if (Character.isLetterOrDigit(s1[i])) {
myStringBuilder.append(s1[i])
}
}
// StringBuilder is complete, grab its final length
var n1 = myStringBuilder.length
// now you can use it
for (i in 0..(n1/2)-1) {
Just fyi, there's also an until operator that works like .. except it doesn't include the last value of the range. So you can write
for (i in 0 until (n1/2))
if you want!
You can use this simple solution.
fun isPalindrome(s:String):Boolean {
val str = s.filter { it.isLetterOrDigit() }.lowercase()
for (i in 0..str.length/2 ){
if (str[i]!=str[str.length-i-1])
return false
}
return true
}
Edit:
By the #cactustictacs comment, you can do this in much more simple way.
fun isPalindrome(s:String):Boolean {
val str = s.filter { it.isLetterOrDigit() }.lowercase()
return str == str.reversed()
}
I'm looking to find the last line of a text file using a rather standard while-loop idiom I find often used in Java.
I have a less compact version working. But the one I would like to use does not appear to be valid syntax in Kotlin. My preferred method includes an assignment and a Boolean test on that assignment in the same line.
Admittedly this is a small matter, but I'm looking to better implement my Kotlin code.
fun readLastLine(file:File):String {
val bufferedReader = file.bufferedReader()
var lastLine=""
//valid
var current = bufferedReader.readLine()
while(current != null) {
lastLine=current
current = bufferedReader.readLine()
}
//return lastLine
//not valid...
//while((current=bufferedReader.readLine())!=null){
// lastLine=current
//}
//responding to comment below,
//preferred/terse answer using file.readLines
//this reads all the lines into a list, then returns the last
return file.readLines().last()
}
In Kotlin, an assignment is not an expression whose value is equal to the assigned value.
You can combine two statements using run function in Kotlin. This function returns the value of the the last expression.
var current = ""
while (run {
current = bufferedReader.readLine()
current != null
}) { // or while (run { current = bufferedReader.readLine(); current != null }) {
lastLine = current
}
However, you can further reduce the code using File.forEachLine() in Kotlin.
fun readLastLine(file: File): String {
var lastLine = ""
file.forEachLine { line ->
lastLine = line
}
return lastLine
}
Or shorter,
fun readLastLine(file: File): String {
var lastLine = ""
file.forEachLine { lastLine = it }
return lastLine
}
This uses BufferedReader and closes automatically internally: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/for-each-line.html
I am new to ExtJS. I came across following piece of code:
Ext.String.format('{1}',value+"#abc.com",value);
Now this will create a mailto link. But my query is that how Ext.String.format works and what else can I use it for?
Ext.String.format:
Allows you to define a tokenized string and pass an arbitrary number
of arguments to replace the tokens. Each token must be unique, and
must increment in the format {0}, {1}, etc.
You can look at the source of the function and see it uses the formatRe regex (/\{(\d+)\}/g):
format: function(format) {
var args = Ext.Array.toArray(arguments, 1);
return format.replace(formatRe, function(m, i) {
return args[i];
});
}
Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each token must be unique, and must increment in the format {0}, {1}, etc.
The following Ext.String.format is modified to accept formatters functions (Ext.util.Format)
e.g.
alert(Ext.String.format("{0} {1:usMoney} {2:date('Y-m-d')}", 10, 20, new Date()));
Here is modified code
Code:
Ext.String._formatRe = /{(\d+)(?:\:([\w.])(?:((.?)?))?)?}/g;
Ext.String._argRe = /(['"])(.?)\1\s(?:,|$)/g
Ext.String.format = function(format) {
var args = Ext.Array.toArray(arguments, 1),
fm = Ext.util.Format;
return format.replace(Ext.String._formatRe, function(m, idx, fn, fmArgs) {
var replaceValue = args[parseInt(idx, 10)],
values,
match;
if (fn) {
values = [replaceValue];
while (match = Ext.String._argRe.exec(fmArgs)) {
values.push(match[2]);
}
return fm[fn].apply(fm, values);
}
return replaceValue;
});
};
I'm wondering about JScript.NET private variables. Please take a look on the following code:
import System;
import System.Windows.Forms;
import System.Drawing;
var jsPDF = function(){
var state = 0;
var beginPage = function(){
state = 2;
out('beginPage');
}
var out = function(text){
if(state == 2){
var st = 3;
}
MessageBox.Show(text + ' ' + state);
}
var addHeader = function(){
out('header');
}
return {
endDocument: function(){
state = 1;
addHeader();
out('endDocument');
},
beginDocument: function(){
beginPage();
}
}
}
var j = new jsPDF();
j.beginDocument();
j.endDocument();
Output:
beginPage 2
header 2
endDocument 2
if I run the same script in any browser, the output is:
beginPage 2
header 1
endDocument 1
Why it is so??
Thanks,
Paul.
Just a guess, but it appears that JScript.NET doesn't support closures the same way as EMCAScript, so the state variable in endDocument() isn't referencing the private member of the outer function, but rather an local variable (undeclared). Odd.
You don't have to use new when calling jsPDF here since you're using a singleton pattern. jsPDF is returning an object literal so even without new you'll have access to the beginPage and endDocument methods. To be perfectly honest I don't know what the specifications call for when using new on a function that returns an object literal so I'm not sure if JScript.NET is getting it wrong or the browser. But for now try either getting rid of the new before jsPDF() or change your function to this:
var jsPDF = function(){
var state = 0;
var beginPage = function(){
state = 2;
out('beginPage');
};
var out = function(text){
if(state == 2){
var st = 3;
}
MessageBox.Show(text + ' ' + state);
};
var addHeader = function(){
out('header');
};
this.endDocument = function(){
state = 1;
addHeader();
out('endDocument');
};
this.beginDocument: function(){
beginPage();
};
}
That will allow you to use the new keyword and create more than one jsPDF object.
I've come across the same problem. In the following code, the closure bound to fun should contain only one variable called result. As the code stands, the variable result in the function with one parameter seems to be different to the result variable in the closure.
If in this function the line
result = [];
is removed, then the result in the line
return result;
refers to the result in the closure.
var fun = function() {
var result = [];
// recursive descent, collects property names of obj
// dummy parameter does nothing
var funAux = function(obj, pathToObj, dummy) {
if (typeof obj === "object") {
for (var propName in obj) {
if (obj.hasOwnProperty(propName)) {
funAux(obj[propName], pathToObj.concat(propName), dummy);
}
}
}
else {
// at leaf property, save path to leaf
result.push(pathToObj);
}
}
return function(obj) {
// remove line below and `result' 3 lines below is `result' in closure
result = []; // does not appear to be bound to `result' above
funAux(obj, [], "dummy");
return result; // if result 2 lines above is set, result is closure is a different variable
};
}();