Dividing a string in Javascript with one identified character and an assortment of unknown characters

I need assistance with splitting a string by a specific character, such as a '/'. However, I also require the characters directly preceding the split character up to the space before them to be included in the result.

For instance:

let myStr =

"bob u/ used cars nr/ no resale value i/ information is attached to the vehicle tag bb/ Joe's wrecker service"

I can split by the '/' using

mySplitStr = myStr.split('/');

But the resulting array is like

mySplitStr[1] = "bob u"
mySplitStr[2] = " used cars nr"
mySplitStr[3] = " no resale value i"
etc

What I actually need is to extract the characters just before the '/'.

u nr i etc

This information is crucial in determining how to handle data following the '/'.

Thank you for any help you can provide.

Answer №1

If you want to extract special characters using a regular expression with the split method, you can do the following:

let parts = myStr.split(/\s*(\S+)\/\s*/);

This will place the special characters at every odd position in the resulting array.

let myStr = "bob u/ used cars nr/ no resale value i/ information is attached to the vehicle tag bb/ Joe's wrecker service";
let parts = myStr.split(/\s*(\S+)\/\s*/);

console.log(parts);
.as-console-wrapper { max-height: 100% !important; top: 0; }

To structure the result further, you can use the special character combinations as keys in an object:

let myStr = "bob u/ used cars nr/ no resale value i/ information is attached to the vehicle tag bb/ Joe's wrecker service";
let obj = myStr.split(/\s*(\S+)\/\s*/).reduceRight( (acc, v) => {
    if (acc.default === undefined) {
        acc.default = v;
    } else {
        acc[v] = acc.default;
        acc.default = undefined;
    }
    return acc;
}, {});
console.log(obj);

Answer №2

Here is the solution you've been searching for:

"alice p/ used books n/ no bookmark s/ story is attached to the page tag gg/ Lana's bookshop"
  .split('/')
  .map(splitPart => {
    const wordsInPart = splitPart.split(' ');
    return wordsInPart[wordsInPart.length - 1];
  });

// Result: ["p", "n", "s", "gg", "bookshop"]

Simply splitting by '/' won't suffice. Remember to iterate through each part of the split result and extract the final "word" from it.

Answer №3

Once you have split your string, you will end up with an array containing different elements. The final set of characters within each element is what you are interested in, and you can extract it using the following code snippet:

let mySplitText = myText.split('/');
for(let j = 0; j < mySplitText.length; j++) {
    let mySplitTextElement = mySplitText[j].split(" "); // Split the current text element
    let lastCharacterSet = mySplitTextElement[mySplitTextElement.length -1]; // Extract the last set of characters
    let myCurrentText = mySplitTextElement.splice(mySplitTextElement.length -1, 1); // Remove the last set of characters from the text element
        myCurrentText = mySplitTextElement.join(" "); // Rejoin the text element into a single string
    switch(lastCharacterSet) {
        case "u":
            // Insert your code here
        case "nr":
            // Insert your code here
        case "i":
            // Insert your code here
    }
}

During the initial loop iteration:

// lastCharacterSet is "u"
// myCurrentText is "bob"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Is there a way to transfer a value from one list box to another without needing to refresh the page, by utilizing AJAX,

Is there a way to automatically load Related Course levels in the Course Level Listbox when selecting a Course from the Course list? <script type="text/javascript" src="js/jquery.js"></script> <div>Course:<select name="course_id" id= ...

Using BeautifulSoup to search for XML elements with the find_next method while specifying a single attribute to limit

Any assistance would be greatly appreciated! I am encountering an issue with the output generated from the XML file example provided below. Incorrect output: Emp_F_Name: Jill Emp_M_Name: H Emp_L_Name: Jones Desired output: Emp_F_Name: Jill Emp_M_Name: No ...

Initiate monitoring for child component modifications

I'm looking to disable 'changeDetection' for the parent component while enabling it for the child component. Can you provide an example of how this can be achieved? The parent component contains static data, meaning change detection is not ...

What is the method for utilizing the value component as the key for the second component?

In my JSON data below: [{"id":19,"text":"A-Z CLI 19/03/2015"},{"id":36,"text":"Wavetel Retail1"},{"id":37,"text":"Wavetel A2Z Platinum"},{"id":38,"text":"Wavetel A2Z Gold"},{"id":40,"text":"mysql test2"},{"id":63,"text":"inbound test"},{"id":137,"text": ...

Enabling onClick based on conditions

I'm struggling to disable a Link onClick when a certain condition is not met. Attempted to move the logic outside of render using a function, but the button always ends up disabled. Tried CSS to disable click, only to realize that tab and enter can ...

Is there a way to identify and count duplicate data-items within an array, and then showcase this information using a react view?

If we have an array like this: [{id: 1, name: "chocolate bar"}, {id:2, name: "Gummy worms"}, {id:3, name:"chocolate bar"}] Is there a way to show on the dom that we have "2 chocolate bars and 1 Gummy Worms"? ...

Issues encountered when attempting to send a JSON object from Javascript to a Servlet using AJAX

I've been attempting to send a JSON object to a servlet using AJAX, but I'm running into an issue where the object is showing up as null in the servlet. Can't seem to pinpoint the problem in this code. JAVASCRIPT function submitValues(even ...

Menu toggle vanishes suddenly

Whenever I click the toggle button, I notice that the menu (which I have set to appear on toggle) only shows for a brief moment before disappearing. As a beginner in bootstrap, I am sure I might have made some obvious mistakes. Any assistance would be gr ...

issue with the emit() and on() functions

While diving into my study of nodejs, I encountered a puzzling issue where emit() and on() were not recognized as functions. Let's take a look at my emitter.js file function Emitter(){ this.events = {}; } Emitter.prototype.on = function(ty ...

What is preventing React CLI from installing the template as TypeScript?

When I run npm init react-app new-app --template typescript, it only generates a Javascript template project instead of a Typescript one. How can I create a Typescript project using the CLI? Current Node JS version: 15.9.0 NPM version: 7.0.15 ...

Access and retrieve pkpass files from a server using React

I've exhausted all options but still can't get it to work. I'm attempting to create an Apple wallet pass using https://github.com/walletpass/pass-js. When I download the pass on the node server where I've implemented it, everything work ...

What is the process for automatically disabling a checkbox based on the condition that the value in another field is 0?

Before we proceed, feel free to check out the jsFiddle example provided: https://jsfiddle.net/1wL1t21s/ In my scenario, there are multiple checkboxes for selecting toppings with a quantity adjustment feature using the plus (+) and minus (-) buttons. Curre ...

Issue with Next.js: Callback function not being executed upon form submission

Within my Next.js module, I have a form that is coded in the following manner: <form onSubmit = {() => { async() => await requestCertificate(id) .then(async resp => await resp.json()) .then(data => console.log(data)) .catch(err => console ...

Load divs, images, or scripts as they enter the viewport

Upon visiting the website , you may notice that certain elements are loaded only when they enter the viewport. I am interested in learning how to implement this feature and am curious about the specific JavaScript or CSS3 techniques utilized for achieving ...

Loading indicator displayed at the top of a div using JavaScript/jQuery

My current challenge involves implementing a progress bar, similar to the pace.js progress bar. The issue arises when the browser is refreshed, as the pace.js progress bar loads on top of the body instead of within a specified div. It is important that the ...

What is the significance of [Function: bound ] in the context of node debugging?

So I was trying to debug my .js file using node debug and when I used catch(error) { It only displayed [Function: bound ] when I tried console.dir(error) What is causing this issue? How can I access the full error object? And how do I retrieve the stack ...

The Echart bar graph is not displaying when trying to use JSON data

Seeking assistance as a beginner in building Basic Bar inverted axes using json data. I am trying to achieve a chart similar to Bar Inverted Axes, but encountering issues with the chart not displaying properly. Utilizing Angular to develop the web applicat ...

Adjusting the content of a single text box by typing in another

Is it feasible to automatically convert a Nepali date input in one textbox into an English date and display it in another textbox without any page refresh? I have a PHP function that can translate dates between Nepali and English, and I want it to execute ...

javascript issue with onchange query

The JavaScript snippet below is included in the head section of my file. <?php echo "<script language='JavaScript'>\n"; echo "var times = new Array();\n"; echo "times[0] = 0;\n"; foreach($times as $time) { echo "times[". ...

Sending empty parameter data via Ajax to an MVC controller

Initially, I had no issues passing a single parameter to my MVC Controller through Ajax. However, when I attempted to add an extra parameter, both parameters stopped sending data to the Controller. Can anyone help with this issue? Thank you! Ajax Code: ...