I have a string and I want to extract a particular string from the given string using a regular expression. I tried with the help of string split. But that takes a lot of processing to achieve the answer. The string to be extracted is emr_cluster:

var str = "edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;exitX=0.915;exitY=0.5;exitPerimeter=0;entryX=0;entryY=0.5;entryPerimeter=0;jettySize=auto;orthogonalLoop=1;outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.emr_cluster;fillColor=#F58534;gradientColor=none;";

How can I extract emr_cluster and get the value?

2 Answers

0
AZ_ On Best Solutions

you can use String.prototype.match

var str = "edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;exitX=0.915;exitY=0.5;exitPerimeter=0;entryX=0;entryY=0.5;entryPerimeter=0;jettySize=auto;orthogonalLoop=1;outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.emr_cluster;fillColor=#F58534;gradientColor=none;";
let out = str.match(/shape=.*\..*\.(.*?);/)[1];
console.log(out)

0
gavgrif On

If it is the shape that is the intended string and the source of that shape is always sourced from "mxgraph.aws3." - then you can split it on that - and then split on the next ";" character to get the shape value you are after.

var str = "edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;exitX=0.915;exitY=0.5;exitPerimeter=0;entryX=0;entryY=0.5;entryPerimeter=0;jettySize=auto;orthogonalLoop=1;outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.emr_cluster;fillColor=#F58534;gradientColor=none;";

var shape = str.split('mxgraph.aws3.')[1].split(';')[0];

console.log(shape) // gives "emr_cluster"

if it is a differennt source - then you can so the same - burt split on the "shape=" to get the full source of the shape property.

var str = "edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;exitX=0.915;exitY=0.5;exitPerimeter=0;entryX=0;entryY=0.5;entryPerimeter=0;jettySize=auto;orthogonalLoop=1;outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape=mxgraph.aws3.emr_cluster;fillColor=#F58534;gradientColor=none;";

var shape = str.split('shape=')[1].split(';')[0];

console.log(shape) // gives "mxgraph.aws3.emr_cluster"