logo
down
shadow

How to split string between 2 patterns in javascript


How to split string between 2 patterns in javascript

By : LightbulbCoder
Date : November 21 2020, 07:01 PM
Hope that helps Feel free to down-vote, but I'd solve it like this (slower than pre-compiled regex):
code :
function myFunc(s) {
    let i = s.lastIndexOf("_");
    let j = s.indexOf(".", i);
    return s.substring(i+1, j);
}

console.log(
    myFunc("test_halloween Party 10 AM - 12:30 PM party_560.json"),
    myFunc("Kaulampur 1110 reva_2018  RR_999 Roadrover_4987.json")
);
function myFunc(s) {
  const MAX = 10;
  t = s.substr(-MAX);
  for (let i=0; i<MAX; i++) {
    let z = "";
    if (t[i] === "_") {
      i++;
      if (isd( t[i] )) {
        z += t[i];
        i++;
        if (isd( t[i] )) {
          z += t[i];
          i++;
          if (isd( t[i] )) {
            z += t[i];
            i++;
            const IS_DOT = 1;
            const IS_DIGIT = 2;
            let x = (t[i] === ".")
              ? IS_DOT 
              : (isd(t[i]))
                ? IS_DIGIT
                : 0;
            OUT:
            while (true) {
              switch (x) {
              case IS_DOT:
                i++;
                if (t.substring(i) === "json") {
                  return z;
                }
                break;
              case IS_DIGIT:
                z += t[i];
                i++;
                x = IS_DOT;
                break;
              default:
                break OUT;
              }
            }
          }
        }
      }
    }
  }
  return null;
}

function isd(c) {
  let x = c.charAt(0);
  return (x >= "0" && x <= "9");
}

console.log(
    [
        "_asnothusntaoeu_2405.json",
        "_asnothusntaoeu_105.json",
        "_asnothusntaoeu_5.json",
        "_asnothusntaoeu.json",
        "_asnothusntaoeu_5json",
        "_asnothusntaoeu_5.jso",
        "_asnothusntaoeu_105.json"
    ].map(s => myFunc(s))
);


Share : facebook icon twitter icon
C# Regex.Split with many string patterns more than 20

C# Regex.Split with many string patterns more than 20


By : John Hobson
Date : March 29 2020, 07:55 AM
With these it helps You're using the static Split method of the Regex class. There's also a Split method on Regex instances, for example:
code :
new Regex(@"(LINE|3DFACE|3DSOLID)").Split(originalString, 5, 0);
"LIGHT||LWPOLYLINE"
"MLEADER|MLEADERSTYLE"
"MLEADERSTYLE"
String.split() by one of two patterns

String.split() by one of two patterns


By : Lost in Java
Date : March 29 2020, 07:55 AM
I wish this helpful for you I want to split this string: 315-045/10-20 to this array: ["315","045","10","20"], meaning it should be split around every occurrence of '/' or '-'. Is it possible to do it with one call to the split() function? , You can use a regex which accepts both slashes and dashes.
code :
String input = "315-045/10-20";
String[] output = input.split("[/-]");
split a string by the last patterns

split a string by the last patterns


By : user3249737
Date : March 29 2020, 07:55 AM
wish of those help I have some data like this: , Try
code :
Col1 <- gsub('uid=(\\d+).*', '\\1', vtab$V1)
Col2 <- gsub('.*dc=(.*)(,dc=.*){2}', '\\1', vtab$V1)
data.frame(Col1, Col2)
#     Col1   Col2
#1 123455 planej
#2 123456  plant
#3 123457   sero
#4 123458   sero
#5 123459   sero
#6 123450   sero
Split string by unique patterns

Split string by unique patterns


By : Ethan Kang
Date : March 29 2020, 07:55 AM
around this issue I was convinced that Edward Peters had the answer. But empirically it seems like all three solutions are equally good:
code :
from random import choice

def edward_peters(string):
    sequences = [[]]
    for end in range(1, len(string) + 1):
        def candidate_sequences():
            for previous_end in range(max(0, end - 10), end):
                substring = string[previous_end:end]
                if len(substring) == len(set(substring)):
                    yield sequences[previous_end] + [substring]

        sequences.append(min(candidate_sequences(), key=len))
    return sequences[-1]

def brendan_abel(long_string):
    if not long_string:
        return []
    cur_i = None
    cur_s = None
    max_i = None
    max_s = None
    for i, s in enumerate(long_string):
        if cur_s is None or s in cur_s:
            if cur_s and (max_s is None or len(cur_s) > len(max_s)):
                max_i = cur_i
                max_s = cur_s
            cur_i = i
            cur_s = [s]
        else:
            cur_s.append(s)
    else:
        if cur_s and (max_s is None or len(cur_s) > len(max_s)):
            max_i = cur_i
            max_s = cur_s
    before = long_string[:max_i]
    after = long_string[max_i + len(max_s):]
    return brendan_abel(before) + [''.join(max_s)] + brendan_abel(after)

def ruud(string):
    result = []
    current = ''
    for c in string:
        if c in current:
            result.append(current)
            current = c
        else:
            current += c
    result.append(current)
    return result

def main():
    while True:
        string = ''.join(choice('1234567890') for _ in range(10000))
        results = [func(string) for func in [edward_peters, brendan_abel, ruud]]
        assert all(''.join(result) == string for result in results)
        assert len(set(map(len, results))) == 1

main()
print edward_peters(string)
['49', '9', '3849', '3089', '91', '1', '15', '58', '42876', '81926', '6720', '90', '0', '27103', '3064', '436', '6', '862', '2', '201', '7091', '912', '23', '6345', '582', '382', '2', '82457', '64937', '0574', '2743', '983', '4382']
How to split a string by multiple patterns in javascript?

How to split a string by multiple patterns in javascript?


By : user2688127
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Sine you want space and punctuation marks to also act as seperators, add \s+ and [.,!?;] to the list of given patterns. join the array with | and create a dynamic regex using RegExp. Add a capturing group wrapper () to preserve the separators when the string is split. filter the empty strings from the array
code :
const str = "There are some strings in my question.",
      patterns = ["Th", "er"];
      
patterns.push('\\s+', '[.,!?;]');

const regex = new RegExp(`(${patterns.join('|')})`, 'i')
const splits = str.split(regex).filter(a => a)

console.log(regex)
console.log(splits)
Related Posts Related Posts :
  • Javascript compiled or not? Check inside
  • Create a Count Up Timer in Javascript/Jquery
  • In Javascript, what's better than try/catch for exiting an outer scope?
  • Using JavaScript regex to strip substring that contains parentheses
  • jquery split() and indexOf results in "Object doesn't support this property or method"
  • ActionScript to Javascript cross-compiler
  • TinyMCE and pluploader not working together
  • Writing to a new window with javascript... get access denied
  • Differences between testing JavaScript and testing Ajax?
  • What JavaScript functions are supported by different browsers?
  • passing input text value to ajax call
  • Can JavaScript load raw bytes to use in HTML5 Canvas?
  • html form.input.value is not getting printed why?
  • A good way to redirect with a POST request?
  • Detect blocked pop-up in Chrome
  • javascript location.hash refreshing in IE
  • Sproutcore: adding a custom stylesheet or script
  • Display tabs like FireFox's on my website
  • JavaScript - get detailed information about the browser
  • Javascript mouse event not captured properly when mouse moved very fast
  • Large number array compression
  • Is it possible to use a string variable to reference an element in Javascript?
  • remove params from form request
  • How to prevent direct access to my JSON service?
  • Trigger Div Click From Link
  • JavaScript multithreading in IE6?
  • Variable scoping and the jQuery.getJSON() method
  • How can I Mimic Gmail's Basic HTML option
  • jQuery.ui.draggable.js and jQuery.ui.widget.js conflict
  • Row rendering in Qooxdoo
  • Google Maps: How does Trulia create their custom InfoWIndows?
  • How can I create an automatically generated alteranate table row color?
  • this fadeIn / fadeOut jQuery code crashes my browsers- Why?
  • call a server side python script from javascript
  • Code Colorer Being Used
  • dynamically create element using javascript
  • jQuery to check if returned data object is empty
  • JQuery hover problem
  • JavaScript Object Question
  • handling date for a mobile app using firebase as backend
  • Vuetify issue - why doesn't the v-img component display anything despite the image being passed in from a valid source?
  • How to sort an array with dynamic property?
  • Comparing property of an object in an array with another array
  • Resolve sibling folder in JavaScript Function
  • Simplify my jQuery code, which is growing huge and redundant
  • How to get row count for jqGrid?
  • Problem with Javascript object and accessing property which exists
  • JQuery: How to AutoComplete "City, State"?
  • javascript REGex remove single quote in match
  • How can I get the size of a file using JavaScript (preferably using MooTools 1.2)?
  • How to determine which date is on friday?
  • Generating thumbnails using jquery or javascript
  • Convert first letter of each word in a string to Uppercase in JavaScript
  • How to set background image of element to user uploaded image
  • How to keep the variable from returning to original value each time I use the onClick event
  • Using jsPDF to create a PDF from an iframe
  • Function Param not defined
  • What's so special about Monads in Kleisli category?
  • Some encoded Javascript that I need in plain text
  • How can I dynamically load and execute all of the Javascript files in a directory?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk