How to obtain the value of TR in JavaScript?

Objective:
Extract the value "2TR" from "MARSSTANDGATA132TR" using JavaScript.
Need to determine the location of the digit 2 within the extracted string.

Issue:
Uncertain about the correct syntax to achieve this task.

Additional Details:
*The characters "TR" always appear at the end of the word.
*The digit "2" in "2TR" is individual and not part of a bigger number.
*Both the word and the address number vary.
*If the regex code fails to locate "TR" at the end of the word, the desired outcome cannot be retrieved.

function myFunction() {
    var str = "MARSSTANDGATA132TR"; 
    var n = str.search("TR");
    document.getElementById("demo").innerHTML = n;
}
<button onclick="myFunction()">Test</button>

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

Appreciate your help!

Answer №1

To easily detect the characters "TR" at the end of a string, regex is not necessary.

You can simply check the last two symbols of the string; if they are "TR", then take the third symbol from the end - otherwise, handle any errors that may occur:

var str = "MARSSTANDGATA132TR";

if (str.slice(-2) == 'TR') {
  console.log(''+str.slice(-3, -2) + ' and index is ' + (str.length - 3));
} else {
  console.log('no TR');
}

Answer №2

Suppose you prefer using the index to locate the correct tr and num idx:

let str = "MARSSTANDGATA132TR"; 
let tr = str.search("TR"), numIdx;

if (tr !== -1) {
  numIdx = str[tr -1];      
  tr = str.substr(tr, tr + 1);
} else {
  alert('no TR');
}
console.log(tr);
console.log(numIdx)

If there are multiple instances of TR in the string, then ensuring that you have identified the right one is crucial.

let str = "MARSS**TR**ANDGATA132**TR**"; 
let trIdx = 0, tr, numIdx;

let findTrIdx = (str) => {
  let tmpIdx = str.search('TR');
  if (!parseInt(str[tmpIdx - 1])) {
    let newStr = str.substr(tmpIdx + 2, str.length -1);
    tmpIdx = tmpIdx + 2;
    findTrIdx(newStr);
  } 
  trIdx += tmpIdx;
  return trIdx;
}

trIdx = findTrIdx(str);

if (trIdx !== -1) {
    numIdx = str[trIdx -1];
  tr = str.substr(trIdx, trIdx + 1);
} else {
    alert('no TR');
}
console.log(tr);
console.log(numIdx)

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

Issue with using jQuery and parseDouble

I have been dealing with an AJAX request that retrieves a JSON object containing multiple values, each with two decimal points. However, the issue is that when these values are returned as part of the JSON, they are in string format. My goal is to perform ...

Accessing a peaceful API and displaying the outcome on a webpage using Node.js

I am currently working on a project that involves fetching data from a RESTful API and displaying the results on an HTML webpage using Node.js. While my code is running smoothly, I would like to ensure that the RESTful request is made every time the webp ...

Find the value of a JavaScript string variable using an alternative name

My latest JavaScript function is designed to fetch JSON data from either a server or local files on any browser. This piece of code processes JSON from two sources: an XMLHttpRequest response, or a variable imported via script. In the case of the latter, ...

Is jQuery's $.trim() function reliable or poorly implemented?

$.trim() utilizes a specific RegExp pattern to trim a string: /^(\s|\u00A0)+|(\s|\u00A0)+$/g However, this can lead to some issues, as demonstrated in the following example: var mystr = ' some test -- more text ...

Step-by-step guide on populating a state using an array

I am having trouble populating a list within a state using the set method, as the state remains empty App.js // Initiates the secrets word game const startGame = () => { // pick word and pick category const { word, category } = pickWordAndCat ...

To begin, select and upload two files for processing. Once complete, you can download the newly generated

I'm encountering difficulties attempting to upload two files to a php script and have the page download a newly merged file without redirecting to a different page. I do not wish to store any files on the server due to their potential size (2MB) as b ...

Modifying an Object within a for-in loop

Hi there, I'm facing a challenge with updating an object that has child properties in my Angular application. Here is the initial object: $scope.osbStep = { test0Nav : { current : false, comp ...

Transferring information between AngularJS and Express/Node without using AJAX

My application is built using AngularJS on a node/express backend, with user authentication handled by passport. After a user signs in or signs up, the communication between my Angular controllers and express is done through $http ajax/xhr calls. The form ...

Dynamically and asynchronously loading numerous LinkedIn share buttons on a page

On my page, I have a grid of post thumbnails that are fetched via AJAX and can be filtered. When a user clicks on a thumbnail, a carousel opens with the selected post centered. In this carousel, each post has a LinkedIn share button integrated. The issue ...

How can I generate a .json file that includes PHP variables?

How can I create a customized JSON file called "file.json.php" using PHP variables such as $_POST['foo']? This file will produce different results based on the value of the post variable passed through an ajax call. What settings do I need to imp ...

Elevate the element from the choice API to the organization API using this.$parent

I recently developed a Vue 3 component called "Tab" using the option API. Here is the code: export default { name: "Tab", props: { name: {required: true}, iconClass: {required: true}, selected: {default: false} }, da ...

What is the best way to compare two arrays in my JSON data?

Hello, I'm trying to compare two arrays - one from my JSON data and the second from a regular array. Specifically, I want to check if the ids of "cm:taggable" exist in my secondArray. JSON { "entry": { "isFile": true, "createdByUs ...

Forward after asynchronous JavaScript and XML (AJAX)

Currently, I am working on an MVC project where I need to achieve the following: The scenario involves sending an ajax request from a JS script and then redirecting to a page along with a model once the request is processed. I attempted to send a form as ...

Transferring class titles between div elements

I would like to implement a feature where class names on div elements shift after a brief delay, perhaps 10 seconds. My goal is for the 3 classes listed below to cycle through the div elements and start over once it reaches the last one. For instance: & ...

Beginning your journey with Mock server and Grunt

Although I have gone through the documentation available at , I am still struggling to get the mockserver up and running despite spending hours on following the instructions provided in the guide. Could someone please outline the precise steps or identify ...

Enhanced coding experience with JavaScript completion and ArangoDB module management

Exploring New Horizons After more than a decade of using Eclipse for Java development, I have decided to delve into the realms of javascript and arangodb due to high demand. My current task involves developing multiple microservices to run within arangodb ...

trouble with synchronizing multiple requests in node express mysql

An expressJS endpoint is connected to a mysql DB, where a query retrieves a set of data and assigns the first returned result to a user by updating a field with the user id. The rule is that a single row can only be allocated to one user until the user pr ...

Uncovering data from a dynamic website through the combination of Selenium and PhantomJS

I am attempting to obtain the timer value from this website http://prntscr.com/kcbwd8 located at , and ideally save it in a variable. import urllib from bs4 import BeautifulSoup as bs import time import requests from selenium import webdriver from urllib. ...

What is the purpose of utilizing "({ })" syntax in jQuery?

What is the purpose of using ({ }) in this context? Does it involve delegation? Can you explain the significance of utilizing this syntax? What elements are being encapsulated within it? For instance: $.ajaxSetup ({ // <-- HERE error: fError, ...

Boosted - Automated Observable with controlled Update alert

Is there a way to create a ComputedObservable in knockout that is computed from non-observable values and manually trigger the Notification? ...