0

I want to remove some text from string or integer using javascipt or jquery..

I have string "flow-[s/c]", "flow-max[s/c]","flow-min[s/c]", "Usage-[s/c]", "temperature"

And I want for each : "flow", "flow-max","flow-min", "Usage", "temperature"

As you can see. I want to remove all the data after - found expect flow-max and flow-min

What I am doing :

var legendName = $(textElement).text().toLowerCase().replace(" ", "-");

Taking the legend Name example : "flow-[s/c]", "flow-max[s/c]"

var displayVal = legendName.split('-')[0];

remove all the data after - found

But I am not able to add condition for flow-max because at this case I will be having two - and two place like flow-min-[s/c]

3 Answers 3

2
var displayVal = $(textElement).text().replace(/\-?\[s\/c\]/, "");

The code /\-?\[s\/c\]/ is a regular expression, where:

  • / at the start and end are the delimiters of the expression.
  • \ is an escape character, indicating that the following character should be taken literally (in our example we need it in front of -, [, / and ] because those are control character for regular expressions).
  • ? means the previous character is optional.

So it replaces an optional dash (-) followed by the text [s/c], with an empty string.

Sign up to request clarification or add additional context in comments.

3 Comments

Or even shorter, but this might cause false positives: legendName.replace(/\-?\[.+/, "");
Could you please describe what the problem is, @JavascriptCoder? What results are you getting? What is your code?
I edited my code slightly, maybe it works better for you now?
1

Just use this simple regex /(max|min)\[.*?]|-\[.*?]/g. The regex is simple, if you see what it does separately.

The logic has been separated by | operator.

legendName = legendName.replace(/(max|min)\[.*?]|-\[.*?]/, "$1");

1 Comment

No: "flow-max[s/c]".replace(/-\[.*?]/g,""); returns "flow-max[s/c]"
0

You can use lastoccur = legendName.lastIndexOf("-"); to find the last occur of "-" and then split your string.

Reference: http://www.w3schools.com/jsref/jsref_lastindexof.asp

1 Comment

This won't work on flow-max[s/c], where the result needs to be flow-max, not flow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.