Glory Raj
Glory Raj

Reputation: 17701

How to get the string just before specific character in JavaScript?

I have couple of strings like this:

I need to grab the string like:

Could any one please help on this using JavaScript? How can I split the string at the particular character?

Many Thanks in advance.

Upvotes: 0

Views: 58

Answers (3)

Yves Kipondo
Yves Kipondo

Reputation: 5623

You can use a regex like this

var data = ["Mar18L7", "Oct13H0L7"];
var regex = /^([a-zA-Z0-9]+)\L[a-zA-Z0-9]+$/;
var output = []
data.forEach(function(el){
    var matches = el.match(regex);
    output.push(matches[1]);
}); 

output variable will be equal to ['Mar18', 'Oct13H0'] and you can join all value usin the .join method on output array

var chain = output.join(" OR ");
// chain will be equal to "Mar18 OR Oct13H0"

Upvotes: 1

Shubham Gupta
Shubham Gupta

Reputation: 2646

Based on input that is given it I have created following function which can take n string in array and return the output in the format you have given. Check if this helps and if some use case is missed.

function generateStr(arr, splitStr) {
  const processedStr = arr.map(value => value.split(splitStr)[0]);
  return processedStr.join(" OR ");
}

console.log(generateStr(["Mar18L7", "Oct13H0L7"], "L7"));

Upvotes: 1

SiddAjmera
SiddAjmera

Reputation: 39482

For var str = 'Mar18L7';

Try any of these:

  1. str.substr(0, str.indexOf('L7'));

  2. str.split('L7')[0]

  3. str.slice(0, str.indexOf('L7'))

  4. str.replace('L7', '')

Upvotes: 3

Related Questions