Split text - get middle of a word only: js-(daniela)Cta - javascript

How to get only the middle of this id attribute:
js-danielaCta
I only want to get the word daniela but this word can be dynamic.
I basically want to remove the "js-" and "Cta" everytime.
How to do this in javascript?

Use a regular expression, match everything in between in a group, and extract that matched group:
const extract = id => id.match(/^js-(.+)Cta$/)[1]
console.log(extract('js-danielaCta'));
console.log(extract('js-abcCta'));
console.log(extract('js-foobarCta'));

This would work unless you will have js- or Cta inside the middle word.
var sample = "js-danielaCta";
var middle = sample.replace("js-","").replace("Cta","");
console.log(middle);
You may be better off using match with regex.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

You can use substring, so if var og =js-danielaCta, then to get the middle, you do the indicies of the start and end letter, so var new = og.substring(3, 9)

Related

Regex in JavaScript, Can I replace only an inner specific group instead of full string?

regex: Morning, ((.*?) (.*?) (.*?) group)
input: Morning, I am inner group
Please see the above code. In this case I would like to replace "inner" to "nested", but I cannot find a way to do this. All the replacement methods I have seen are either for flat grouping (not nested) or replacing the whole line.
May I know if there a way to achieve what I want? Thanks in advance.
It is possible, but you need to specify the d flag as for hasIndices so you can get the indices of a specific group.
Once you get the start and end indices of that group, you can just concatenate the first part and second part with the replacement easily:
const regex = /Morning, ((.*?) (.*?) (.*?) group)/d;
const input = "Morning, I am inner group";
// in this case, you want to get the indices of the 4th group
const [start, end] = input.match(regex).indices[4];
const output = input.slice(0, start) + 'nested' + input.slice(end);
console.log(output);

Replce repeating set of character from end of string using regex

I want to remove all <br> from the end of this string. Currently I am doing this (in javascript) -
const value = "this is an event. <br><br><br><br>"
let description = String(value);
while (description.endsWith('<br>')) {
description = description.replace(/<br>$/, '');
}
But I want to do it without using while loop, by only using some regex with replace. Is there a way?
To identify the end of the string in RegEx, you can use the special $ symbol to denote that.
To identify repeated characters or blocks of text containing certain characters, you can use + symbol.
In your case, the final regex is: (<br>)*$
This will remove 0 or more occurrence of <br> from the end of the line.
Example:
const value = "this is an event. <br><br><br><br>"
let description = String(value);
description.replace(/(<br>)*$/g, '');
You may try:
var value = "this is an event. <br><br><br><br>";
var output = value.replace(/(<.*?>)\1*$/, "");
console.log(output);
Here is the regex logic being used:
(<.*?>) match AND capture any HTML tag
\1* then match that same tag zero or more additional times
$ all tags occurring at the end of the string

How to remove strings before nth character in a text?

I have a dynamically generated text like this
xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0
How can I remove everything before Map ...? I know there is a hard coded way to do this by using substring() but as I said these strings are dynamic and before Map .. can change so I need to do this dynamically by removing everything before 4th index of - character.
You could remove all four minuses and the characters between from start of the string.
var string = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0',
stripped = string.replace(/^([^-]*-){4}/, '');
console.log(stripped);
I would just find the index of Map and use it to slice the string:
let str = "xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0"
let ind = str.indexOf("Map")
console.log(str.slice(ind))
If you prefer a regex (or you may have occurrences of Map in the prefix) you man match exactly what you want with:
let str = "xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0"
let arr = str.match(/^(?:.+?-){4}(.*)/)
console.log(arr[1])
I would just split on the word Map and take the first index
var splitUp = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0'.split('Map')
var firstPart = splitUp[0]
Uses String.replace with regex expression should be the popular solution.
Based on the OP states: so I need to do this dynamically by removing everything before 4th index of - character.,
I think another solution is split('-') first, then join the strings after 4th -.
let test = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0'
console.log(test.split('-').slice(4).join('-'))

Extract Twitter handlers from string using regex in JavaScript

I Would like to extract the Twitter handler names from a text string, using a regex. I believe I am almost there, except for the ">" that I am including in my output. How can I change my regex to be better, and drop the ">" from my output?
Here is an example of a text string value:
"PlaymakersZA, Absa, DiepslootMTB"
The desired output would be an array consisting of the following:
PlaymakersZA, Absa, DiepslootMTB
Here is an example of my regex:
var array = str.match(/>[a-z-_]+/ig)
Thank you!
You can use match groups in your regex to indicate the part you wish to extract.
I set up this JSFiddle to demonstrate.
Basically, you surround the part of the regex that you want to extract in parenthesis: />([a-z-_]+)/ig, save it as an object, and execute .exec() as long as there are still values. Using index 1 from the resulting array, you can find the first match group's result. Index 0 is the whole regex, and next indices would be subsequent match groups, if available.
var str = "PlaymakersZA, Absa, DiepslootMTB";
var regex = />([a-z-_]+)/ig
var array = regex.exec(str);
while (array != null) {
alert(array[1]);
array = regex.exec(str);
}
You could just strip all the HTML
var str = "PlaymakersZA, Absa, DiepslootMTB";
$handlers = str.replace(/<[^>]*>|\s/g,'').split(",");

extract number using regex

I have a string:
name:demo;morestuff.nbvideo:3;morestuff_here:45
from which I need to extract the nbvideo number. I managed it with 2 regexes, but I'm sure it can be done in just one regex.
Here's what I have now:
// get the nbvideo:XX part
videoPart = sink.tag.match(/nbvideo:([0-9]+)/gi);
// get the number from the video part
videoCount = videoPart[0].match(/([0-9]+)/gi)[0];
How can I extract the number behind 'nbvideo:' with one single regex?
Remove g from the modifiers and access the first capture group value like this:
var sink_tag = "name:demo;morestuff.nbvideo:3;morestuff_here:45";
var m = sink_tag.match(/nbvideo:([0-9]+)/i);
if (m) {
videoPart = m[1];
document.body.innerHTML = videoPart; // demo
}
The thing is that string#match does not keep captures if a global modifier is used with a regex, and it seems you just have one nbvideo:<NUMBER> in the input. So, removing /g seems to be enough. Else, use RegExp#exec() in a loop.

Categories

Resources