How to Split String in React Js? - javascript

How to extract "GoogleUpdate.exe" from the string "C:\Program Files (x86)\Google\Update\GoogleUpdate.exe"?

You can do that with a combination of split() and pop():
const str = "C:\\Program Files (x86)\\Google\\Update\\GoogleUpdate.exe";
const parts = str.split("\\");
const fileName = parts.pop();
console.log(fileName); // outputs "GoogleUpdate.exe"
Note: You would need to escape the \ character

In javascript, character '\' is a escape character!
so, if you write your code lolike this:
const tmp = "C:\Program Files (x86)\Google\Update\GoogleUpdate.exe";
console.log(tmp);
you will be got result
C:Program Files (x86)GoogleUpdateGoogleUpdate.exe
if you want keep '\' in your variable, you can manual fix
const tmp = "C:\\Program Files (x86)\\Google\\Update\\GoogleUpdate.exe";
actualy, it's not smart,maybe string template literals is better.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw
const tmp = String.raw`C:\Program Files (x86)\Google\Update\GoogleUpdate.exe`
console.log(tmp);
tmp.split('\\').pop();

It can be extracted from the given string by using the following steps:
Split the string by "". This will create an array of strings where each element is separated by a backslash.
Take the last element of the array, which is "GoogleUpdate.exe".
import React, { useState } from "react";
const Example = () => {
const [string, setString] = useState("C:\\Program Files
(x86)\\Google\\Update\\GoogleUpdate.exe");
const splitString = string.split("\\");
const extracted = splitString[splitString.length - 1];
return (
<div>
<p>Original String: {string}</p>
<p>Extracted String: {extracted}</p>
</div>
);
};
export default Example;

Just use the Split Method:
import React from 'react';
function Example() {
const path = "C:\Program Files(x86)\Google\Update\GoogleUpdate.exe";
const filename = path.split('\').pop();
return (
<div>
<p>The filename is: {filename}</p>
</div>
);
}
export default Example;

Another Way to achive this
import React, { useState } from 'react';
const Example = () => {
const [string, setString] = useState(
'C:\\Program Files (x86)\\Google\\Update\\GoogleUpdate.exe'
);
const splitString = string.split('\\');
const extracted = splitString.pop();
return (
<div>
<p>Original String: {string}</p>
<p>Extracted String: {extracted}</p>
</div>
);
};
export default Example;

Related

Draft js replaceText remove inlineStyles

I implement WYSIWYG editor with draftjs and I have a set of rules for typography fixing. I use Modifier.replaceText to replace what I want, but the problem is, when I call it, it removes inlineStyles in replaced text.
Here is a block of code that I use for typography. Inputs are rules (array with rules) and editorState.
rules.forEach(({ toReplace, replace }) => {
const blockToReplace = [];
let contentState = editorState.getCurrentContent();
const blockMap = contentState.getBlockMap();
blockMap.forEach(contentBlock => {
const text = contentBlock.getText();
let matchArr;
while ((matchArr = toReplace.exec(text)) !== null) {
const start = matchArr.index;
const end = start + matchArr[0].length;
const blockKey = contentBlock.getKey();
const blockSelection = SelectionState.createEmpty(blockKey).merge({
anchorOffset: start,
focusOffset: end,
});
blockToReplace.push(blockSelection);
}
});
blockToReplace.reverse().forEach((selectionState) => {
contentState = Modifier.replaceText(
contentState,
selectionState,
text.replace(search, replace)
);
});
editorState = EditorState.push(editorState, contentState);
});
So, my input is: *bold...*
The wrong output is: *bold*…
Should be: *bold…*
Note: asterisks are for bold designation, change is three dots to horizontal ellipsis (U+2026)
Anybody any idea? I google it for two days and nothing...

How to seperate item in array using react

user.js
import React, { useState, useEffect } from 'react';
import Axios from 'axios';
const RecommendationDetail = () => {
const [image, setImage] = useState([]);
useEffect(() => {
loadRekko();
}, []);
const loadRekko = async () => {
const res = await Axios.get(`http://localhost:3001/dashboard-rekko/${id}`,{
headers:headers
});
console.log(res.data.response);
var array = [];
let a = (res.data.response.rekkoRecords.product_img)
array.push(a)
setImage(array) ====>>> How can i make array like i want
console.log(image)
setRecommendation(res.data.response.rekkoRecords)
}
return (
{image.map((it) => {
return (
<div key={it}>
<img src= {'http://localhost:3001/'+it} />
</div>
)
})}
)
}
Everything is working but I want to show multiple images. I am getting a response in "uploads\classpamplate.png,uploads\classpamplate1.jpg" this format and after pushing it in the array it becomes ["uploads\classpamplate.png,uploads\classpamplate1.jpg"] but what I want is ["uploads\classpamplate.png","uploads\classpamplate1.jpg"] both are separated so that I can show it using .map() function. Any help will be appreciated
You can use .split() to separate that string by comma ,:
The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array.
let a = (res.data.response.rekkoRecords.product_img)
setImage(a.split(','))
See a live example below:
const data = `uploads\classpamplate.png,uploads\classpamplate1.jpg`
const result = data.split(',')
console.log(result)
Just split the string by ,. it will return a new array
let result = (res.data.response.rekkoRecords.product_img).split(',');
let array = [...result];
You can split them using , so that it'll be converted to an array
let a = (res.data.response.rekkoRecords.product_img).split(",");
array.push(...a)
or
Directly you can call setImage like below
setImage(res.data.response.rekkoRecords.product_img.split(","));
Check if the response is empty or not and then split
let a = (res.data.response.rekkoRecords.product_img);
a = a && a.split(",") || []
setImage([...a])
I am assuming
a = "uploads\classpamplate.png,uploads\classpamplate1.jpg"
expected result = ["uploads\classpamplate.png","uploads\classpamplate1.jpg"]
Don't push a in the array, try below
setImage(a.split(','))

Target fragment within react const

I am building my first react site, using gatsby with prismic.io as the CMS for my news section.
Within prismic I am using slices for quotes and featured images in each of the news stories and am looking to try and pull this data into my page, however I am unsure how to target the specific fragment names that I have created within the relevant const that has been set up for each.
GraphQL Query
export const query = graphql`
query ($slug:String){
prismicNewsStory (uid:{eq: $slug}) {
data {
body {
__typename
... on PrismicNewsStoryBodyQuote {
primary {
quote {
text
}
}
}
... on PrismicNewsStoryBodyFeaturedImage {
primary {
featured_image {
url
}
}
}
}
}
}
}
`
Targetting consts
const quote = props.data.prismicNewsStory.data.body[0].primary.quote.text
const featured_image = props.data.prismicNewsStory.data.body[1].primary.featured_image.url
As the slices are optional within prismic, I am encountering issues on some of the news stories when a featured_image is added before a quote, making them swap order within the body.
Question
Is there a way within each const to target a particular fragment or is there a better way for me to do this?
//get the array
const body = props.data.prismicNewsStory.data.body;
const {feature_image : fi0, quote: q0} = body[0].primary;
// above line is equivalent to:
// const fi0 = body[0].primary.feature_image;
// const q0 = body[0].primary.quote;
// when order is reversed q0 will be undefined
const {feature_image : fi = fi0, quote : q = q0} = body[1].primary;
// above line is equivalent to:
// const fi = body[1].primary.feature_image || fi0;
// const q = body[1].primary.quote || q0;
// when order is reversed fi0 will be assigned to fi
const feature_image = fi.url;
const quote = q.text
or use a reduce
const reduceStory = (acc, item) => ({
feature_image: acc.feature_image|| item.primary.feature_image,
quote: acc.quote || item.primary.quote
})
const story = props.data.prismicNewsStory.data.body.reduce(reduceStory, {});
const feature_image = story.feature_image.url;
const quote = story.quote.text
>
After looking and learning a bit more learning with #paul-mcbride we came up with the following solution to target any __typename.
const body = props.data.prismicNewsStory.data.body.reduce((object, item) => ({
...object,
[item.__typename]: item.primary
}), {});
You can now use the targeted slice name.
<FeaturedImage src={body.PrismicNewsStoryBodyFeaturedImage.featured_image.url} />
or
<QuoteText>{body.PrismicNewsStoryBodyQuote.quote.text}</QuoteText>

How to convert react component to html string?

I have found similar to my issue here.
But I have a little bit different scenario. I have string of html rather than just string. So, I wanted to do:
Let's suppose MyComponent is just returning h3 element for now:
const MyComponent = ({children}) => (<h3>{children}</h3>)
var parts = "<h1>I</h1><p>am a cow;</p>cows say moo. MOOOOO."
.split(/(\bmoo+\b)/gi);
for (var i = 1; i < parts.length; i += 2) {
parts[i] = <MyComponent key={i}>{parts[i]}</MyComponent>;
}
// But I need html to be rendered
return <div dangerouslySetInnerHTML={{ __html: parts }} />
This will be rendered in the browser like this:
I
am a cow;
cows say ,[object Object],. ,[object Object],.
What I can think here to resolve the issue is converting component with string of html first.
parts[i] = convertToStringOfHtml(<MyComponent key={i}>{parts[i]}</MyComponent>);
But I don't have idea how to convert component to string of html.
You can do with react-dom
import { renderToString } from 'react-dom/server'
//
//
parts[i] = renderToString(<MyComponent key={i}>{parts[i]}</MyComponent>)
view more here https://reactjs.org/docs/react-dom-server.html
You can also do something like this
import React from "react";
import ReactDOM from "react-dom";
import ReactDOMServer from "react-dom/server";
const Hello = () => <div>hello</div>;
const html = ReactDOMServer.renderToStaticMarkup(<Hello />);
console.log(html.toString());

Check string for array elements and systematically replace them with HTML tags - (JS, ReactJS)

I need to search a string, and if it has any values that match my array, I need to add <span></span> tags to them to add custom CSS. I am using reactJS.
How do I search the string for objects from my array?
Example:
let string = 'this is a message with many inputs, {{input1}}, {{input2}}, and again {{input1}}'
let array = [{parameter: '{{input1}}'},{parameter: '{{input2}}'},...]
findAllOccurrances = () => {???}
Then systematically replace them '{{inputX}}' with <span className='bizarre-highlight'>{{inputX}}</span>
My intent is to add custom CSS to any text in the div which matches my array, so if you got any ideas please shoot! Again, using reactJS if that helps.
I created a component that will replace the elements that need to be highlighted with a span you can test it here
The component is:
import React from 'react';
export default ({ terms, children }) => {
const result = []
const regex = terms.map(escapeRegExp).join('|');
const re = new RegExp(regex);
let text = (' ' + children).slice(1); // copy
let match = re.exec(text);
while (match != null) {
const str = match.toString();
result.push(text.slice(0, match.index));
result.push(<span className="highlighted">{str}</span>);
text = text.slice(match.index + str.length);
match = re.exec(text);
}
result.push(text);
return result;
}
function escapeRegExp (str) {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, "\\$&");
}
And you should use it like this:
import React from 'react';
import Highlighter from './Highlighter';
const terms = [ '{{input1}}', '{{input2}}' ]
const App = () => (
<div>
<Highlighter terms={terms}>
{'this is a message with many inputs, {{input1}}, {{input2}}, and again {{input1}}'}
</Highlighter>
</div>
);
Use String#replace with a RegExp to find all instances of '{{inputX}}', and wrap the matches with the span:
const string = 'this is a message with many inputs, {{input1}}, {{input2}}, and again {{input3}}'
const array = [{parameter: '{{input1}}'},{parameter: '{{input2}}'}]
const pattern = new RegExp(array.map(({ parameter }) => parameter).join('|'), 'g');
const result = string.replace(pattern, (match) =>
`<span className='bizarre-highlight'>${match}</span>`
)
console.log(result)
use Array#map to extract values for wrapping in <span> and then cycle on them for replacement:
let string = 'this is a message with many inputs, {{input1}}, {{input2}}, and again {{input1}}';
let array = [{parameter: '{{input1}}'},{parameter: '{{input2}}'}];
array.map(el => { return el.parameter }).forEach(str => {
string = string.split(str).join("<span className=\'bizarre-highlight\'>" + str + "</span>");
});
console.log(string);

Categories