简体   繁体   中英

How do I have JavaScript get a substring before a character?

Let's say I have a paragraph that says 55+5. I want to have JavaScript return everything before the plus. Is this possible using substrings?

Do you mean substring instead of subscript? If so. Then yes.

var string = "55+5"; // Just a variable for your input.

function getBeforePlus(str){

    return str.substring(0, str.indexOf("+")); 
   /* This gets a substring from the beginning of the string 
      to the first index of the character "+".
   */

}

Otherwise, I recommend using the String.split() method.

You can use that like so.

var string = "55+5"; // Just a variable for your input.

function getBeforePlus(str){

    return str.split("+")[0]; 
    /* This splits the string into an array using the "+" 
       character as a delimiter.
       Then it gets the first element of the split string.
    */

}

Yes. Try the String.split method: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/split

split() returns an array of strings, split by the character you pass to it (in your case, the plus). Just use the first element of the array; it will have everything before the plus:

var string = "foo-bar-baz"
var splitstring = string.split('-')
//splitstring is a 3 element array with the elements 'foo', 'bar', and 'baz'

Use split and shift .

var str = '55+5';

var beforePlus = str.split('+').shift();

console.log(beforePlus);
// -> "55"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM