Home > Software design >  Find a specific value/characters in a string field (If statement)
Find a specific value/characters in a string field (If statement)

Time:02-11

I have these string statments:

  • 10 - Holiday Booking
  • 20 - Summer term
  • 34 - Nighttime
  • Autumn time

I wanted to create a IF statement which says:

If the start of the string contains 'X - ' (a number and a hyphen with spaces, although I think it will recognise the number as a string type), then keep it as it is, otherwise add a random number and hyphen to the start

  • 10 - Holiday Booking
  • 20 - Summer term
  • 34 - Nighttime
  • 55 - Autumn time

I am using Google App Scripts/Java.

CodePudding user response:

You are looking for something like this:

yourArrayOfStrings.map(e => /^\d*\s-\s/.test(e) ? e : `${Math.floor(Math.random()*100)} - ${e}`);
  • Array.prototoype.map(e => ...) loop over array and return modified element

  • Regex: /^\d*\s-\s/ - checks if string starts with number - ...

const strings = ["10 - Holiday Booking", "20 - Summer term", "34 - Nighttime", "Autumn time"];

const res = strings.map(e => /^\d*\s-\s/.test(e) ? e : `${Math.floor(Math.random()*100)} - ${e}`);
console.log(res);

CodePudding user response:

The function can be made like this

const str1 = '10 - Holiday Booking';
const str2 = 'Autumn time';

function MyFun(str) {
  const firstAscii = str.charCodeAt(0);
  if( (firstAscii>=65 && firstAscii<=90 ) || (firstAscii>=65 && firstAscii<=90) ){
    str = Math.floor((Math.random() * 100)   1)   " - "   str;
  }
  console.log(str);
}

MyFun(str1);
MyFun(str2);
  • Related