Home > Mobile >  How to Split String in React Js?
How to Split String in React Js?

Time:02-02

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

CodePudding user response:

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

CodePudding user response:

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();

CodePudding user response:

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;

CodePudding user response:

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: {extracteenter code hered}</p>
    </div>
  );
};

export default Example;

CodePudding user response:

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;

  • Related