How to find and replace text using regex? - javascript

I have the following text as an input.
This is specified input. This is Specified input.
And I want the below output.
This is <span>specified</span> input. This is <span>Specified</span> input.
If I do str.replace(\specified\gi, '<span>specified</span>') it will replace like this
This is <span>specified</span> input. This is <span>specified</span> input.
How can I replace this string with the matched element

Replace with <span>$&<span> to insert the matched text:
const str = 'This is specified input. This is Specified input.';
const result = str.replace(/specified/gi, '<span>$&<span>');
console.log(result);

Use $& to retrieve the matched string.
You also have the wrong kind of slash around your regexp.
var str = "This is specified input. This is Specified input.";
console.log(str.replace(/specified/gi, '<span>$&</span>'));

Related

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

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

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)

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(",");

Modify regex matches inside the replacement string

I've a problem with some regex to grab url's from a text and modify all matches inside the replacement string again by a function.
The code below is a dummy example of what I want do to.
Is something like this possible?
var exp = /\b((http:\/\/|https:\/\/)[\S]*)/g;
text = text.replace(exp, "");
Supply a function as 2nd argument to .replace:
var exp = /\bhttps?:\/\/[\S]*/g;
text = text.replace(exp, function ($0) {
return ''
});
(Note that $0 is just a variable name, you can name it differently).
Check String.replace's documentation on MDN for the meaning of the arguments to the replacement function. The first argument is the text capture by the whole regex. Then the next N arguments are the text captured by the N capturing groups in the regex.
I also take my liberty to rewrite the regex. Since \b is an assertion, no text will be consumed.

Extracting strings from an input field using regular expressions and jQuery

I am trying to match a string in an input field using a regular expression /[1-9][a-zA-Z]/ and insert it into a <p> tag using jQuery.
I modified this example from the jQuery API docs to include the following if statement. When I type '1A' in the input field it works, however I want to exclude the rest of the string so that the <p> only includes the matched string portion.
$("input").keyup(function () {
if($(this).val().match(/[1-9][a-zA-Z]/)){
var value = $(this).val();
};
$("p").text(value);
}).keyup();
Did I explain that clearly? Could anyone point me in the right direction?
Much appreciated,
So what you are doing in the above code is that if the value of the input field matches the regular expression, you assign its value to <p> tag. Since, you want to assign the matched string to the <p> tag, you should do:
$("input").keyup(function () {
var match = $(this).val().match(/[1-9][a-zA-Z]/);
if(match){
var value = match[0]; // Your problem was here
};
$("p").text(value);
}).keyup();
The match method of a String returns an array containing the match if it passed or undefined if the match failed.

Categories

Resources