Javascript String Processing

I have a line as shown below:

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

He may not have. terms to numerical 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 get only terms before the numeric values ​​in this line. i.e. "SSI-ROAM-Synergy" or "LCD-SSI-ROAM-Synergy"

I use like this:

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

but how to get only terms before numerical values.

+3
source share
4 answers

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 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
+3
source

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>
0
source
b="LCD-SSI-ROAM-Synergy-111-222-LLX".match(/^.+?-[0-9]/)[0].split("-");
b.pop();

b ["LCD", "SSI", "ROAM", "Synergy"]

0

indexOf, match 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));
0

All Articles