trying to break the string into multiple sections

129 Views Asked by At

I have the string value as:

Half Day Morning (9:00 AM - 11:30 AM)  (M/T/W/TH/F)

i am using coldfusion code using replace but that is not working

using either javascript or jquery or any server side, i am trying to break this code it to like this

  1. Half Day Morning 
    2. 9:00 AM - 11:30 AM 
    3. M/T/W/TH/F 

any idea how can i do it, plan to use regex but not sure if the server side regex will make it or not, i a using cold fusion

am i am using a cfoutput query around the rows

4

There are 4 best solutions below

3
On

Modified to show how to do it with query results

Here is a way to do it with ColdFusion code:

<cfoutput query="NameOfQuery">
    <cfset StringAsList = Replace(FieldFromQuery, ")", "", "all")>
    <cfloop index="LoopCounter" from="1" to="#ListLen(StringAsList, '(')#">
    #LoopCounter#. #ListGetAt(StringAsList, LoopCounter, "(")#<br>
    </cfloop>    
</cfoutput>

You can mess around with it here.

0
On

If the string is always formatted like that with parenthesis a simple split should do the trick

var str = "Half Day Morning (9:00 AM - 11:30 AM)  (M/T/W/TH/F)";
str.replace(")", "");
var res = str.split("(");

var str1 = "1. " + res[0].trim();
var str2 = "2. " + res[1].trim();
var str3 = "3. " + res[2].trim();

0
On

You can try this regex as demonstrated here in PHP.

Outputs:

1. Half Day Morning
2. 9:00 AM - 11:30 AM
3. M/T/W/TH/F

Code:

<?php

$s = 'Half Day Morning (9:00 AM - 11:30 AM)  (M/T/W/TH/F)';


if (preg_match('/([^\(]+)\s+\(([^\)]+)\)\s+\(([^\)]+)\)/', $s, $matches) === FALSE)
// preg_last_error_msg() available since PHP 8 which is now out!
    die('preg_match() failed: ' . preg_last_error_msg());

foreach ($matches as $num => $text)
{
    if ($num)
        echo "$num. $text\n";
}
0
On

use split() and access it by index value

function myFunction() {
  var str = "Half Day Morning (9:00 AM - 11:30 AM)  (M/T/W/TH/F)";
   str = str.replaceAll(")", "");
   var res = str.split("(");
  document.getElementById("demo").innerHTML = "1. "+res[0]+"<br> 2. "+ res[1]+"<br> 3. "+ res[2];
}
<!DOCTYPE html>
<html>
<body>
 Half Day Morning (9:00 AM - 11:30 AM)  (M/T/W/TH/F)
 <br>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

</body>
</html>