3

I have a string like this below:

var st = "ROAM-Synergy-111-222-LLX "

It can have any no. of terms before the numeric values ..ie. its possible formats are:

var st = "SSI-ROAM-Synergy-111-222-LLX "     or
var st = "LCD-SSI-ROAM-Synergy-111-222-LLX"  etc..

Now I need to fetch only the terms before numeric values in this string. ie. "SSI-ROAM-Synergy" or "LCD-SSI-ROAM-Synergy"

I am using like this:

var finalString = st.split("-");

but how to get only the terms before numeric values.

2
  • Could there also be strings without any numeric values? Commented Feb 17, 2014 at 7:31
  • no no..the original string must have some numeric codes.. i.e "111-222-LLX" or "333-444-LLX" etc. Commented Feb 17, 2014 at 7:35

4 Answers 4

3

You can use:

var myval = st.match(/^\D+(?=-)/)[0];
//=> SSI-ROAM-Synergy OR LCD-SSI-ROAM-Synergy

Explanation:

^ assert position at start of the string
\D+ match any character that's not a digit [^0-9]
Quantifier: Between one and unlimited times, as many times as possible
(?=-) Positive Lookahead - Assert that the regex below can be matched
- matches the character - literally
Sign up to request clarification or add additional context in comments.

3 Comments

one thing i noticed is..if I pass this string ie. "nLight-SSI-RELOC-RTLED-Synergy-345-777-LLA Replacement" ....then it is returning only "nLight-SSI-RELOC-RTLED" Can u pls check ?
It actually returns nLight-SSI-RELOC-RTLED-Synergy when input is nLight-SSI-RELOC-RTLED-Synergy-345-777-LLA Replacement Is that incorrect?
Thanks for confirming again. I am using this in my code and its the only issue i am facing...let me check again..i might be doing something wrong...
0

try with the following code

<script>
        var yourString = "ROAM-Synergy-111-222-LLX ";
        var output=retriveStartString(yourString);
        alert(output);

    function retriveStartString(inputString){
        var newString="";
        for (i=0;i<inputString.length;i++) {
            var subStr=inputString.substr(i,1);
            //alert(subStr);
            if(subStr.charCodeAt(0)>=48 && subStr.charCodeAt(0)<=57){
                break;
            }
            else{
                newString+=subStr;
            }
        }
        return newString;
    }
    </script>

Comments

0
b="LCD-SSI-ROAM-Synergy-111-222-LLX".match(/^.+?-[0-9]/)[0].split("-");
b.pop();

Here output of b will be ["LCD", "SSI", "ROAM", "Synergy"]

Comments

0

Here is another way using a combination of indexOf, match and substr.

var st = "ROAM-Synergy-111-222-LLX";
var lIdx = st.indexOf(st.match(/-\d/));
console.log(st.substr(0, (lIdx >= 0) ? lIdx : st.length));

Comments

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.