replacing numbers in a string with regex in javascript - javascript

I have string that contains numbers and characters. I want to replace the numbers with another value that will give it a css class of someClass.
Now I got the code to detect all the numbers in the string and replace it with something else.
My question is how do I get the current number match and put it to the new string or value that will replace the original one?
Basically what I want to happen is:
for example, I have this string: 1dog3cat, I want it to get replaced with <span class="someClass">1</span>dog<span class="someClass">3</span>cat
Here's my current code:
var string_variable;
string_variable = "1FOO5,200BAR";
string_variable = string_variable.replace(/(?:\d*\.)?\d+/g, "<span class='someClass'>" + string_variable + "</span>");
alert(string_variable);

Simply remember the matched pattern using parenthesis and retrieve that value using $1 and add span tag to it.
Use this regex
string_variable = string_variable.replace(/(\d+)/g, "<span class='someClass'>$1</span>");
See DEMO

Related

removing specific html tags in a string - javascript

I'm trying to clean up a string of text on the server side from the output generated by a wysiwyg. and while I can fix it client side, it's best to also fix this on the server side.
var string = "<p>firstline</p><p>secondline</p><p>thirdline</p><p>iframe</p><p>a</p><p>df</p><p>dsf </p><p><br></p><p>sd</p><p>f</p><p>sdf</p><p><br></p>"
var x = string.replace("<p><br></p>", "");
https://jsfiddle.net/8c0yh9r7/
the code should but doesn't get rid of the break within the paragraphs
why is that?
Use a regex with a global flag, like:
string.replace(/<p><br><\/p>/g, "");
https://jsfiddle.net/Lu2r3820/1/
When using a string only the first occurrence will be replaced.
See replace() documentation
doesn't get rid of the break within the paragraphs
Yes, it does… but only once. You have more than one paragraph containing a line break in your code.
If you want to replace it more than once, you need to use a regex and mark it as global with g.
var x = string.replace(/<p><br><\/p>/g, "");
It does replace, but only the first occurrence. If you run this afterwards, you can see the second occurrence disappearing.
var x = x.replace("<p><br></p>", "");
refer to this to replace all occurrences.
How to replace all occurrences of a string in JavaScript?

why isn't this javascript regex split function working?

I'm trying to split a string by either three or more pound signs or three or more spaces.
I'm using a function that looks like this:
var produktDaten = dataMatch[0].replace(/\x03/g, '').trim().split('/[#\s]/{3,}');
console.log(produktDaten + ' is the data');
I need to clean the data up a bit, hence the replace and trim.
The output I'm getting looks like this:
##########################################################################MA-KF6###Beckhoff###EL1808 BECK.EL1808###MA-KF7###Beckhoff###EL1808 BECK.EL1808###MA-KF12###Beckhoff###EL1808 BECK.EL1808###MA-KF13###Beckhoff###EL1808 BECK.EL1808###MA-KF14###Beckhoff###EL1808 BECK.EL1808###MA-KF15###Beckhoff###EL1808 BECK.EL1808###MA-KF16###Beckhoff###EL1808 BECK.EL1808###MA-KF19###Beckhoff###EL1808 BECK.EL1808 is the data
How is this possible? Irrespective of the input, shouldn't the pound and multiple spaces be deleted by the split?
You passed a string to the split, the input string does not contain that string. I think you wanted to use
/[#\s]{3,}/
like here:
var produktDaten = "##########################################################################MA-KF6###Beckhoff###EL1808 BECK.EL1808###MA-KF7###Beckhoff###EL1808 BECK.EL1808###MA-KF12###Beckhoff###EL1808 BECK.EL1808###MA-KF13###Beckhoff###EL1808 BECK.EL1808###MA-KF14###Beckhoff###EL1808 BECK.EL1808###MA-KF15###Beckhoff###EL1808 BECK.EL1808###MA-KF16###Beckhoff###EL1808 BECK.EL1808###MA-KF19###Beckhoff###EL1808 BECK.EL1808";
console.log(produktDaten.replace(/\x03/g, '').trim().split(/[#\s]{3,}/));
This /[#\s]{3,}/ regex matches 3 or more chars that are either # or whitespace.
NOTE: just removing ' around it won't fix the issue since you are using an unescaped / and quantify it. You actually need to quantify the character class, [#\s].

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

Regex with multiple start and end characters that must be the same

I would like to be able to search for strings inside a special tag in a string in JavaScript. Strings in JavaScript can start with either " or ' character.
Here an example to illustrate what I want to do. My custom tag is called <my-tag. My regex is /('|")*?<my-tag>((.|\n)[^"']*?)<\/my-tag>*?('|")/g. I use this regex pattern on the following strings:
var a = '<my-tag>Hello World</my-tag>'; //is found as expected
var b = "<my-tag>Hello World" + '</my-tag>'; //is NOT found, this is good!
var c = "<my-tag>Hello World</my-tag>"; //is found as expected
var d = '<my-tag>something "special"</my-tag>'; //here the " char causes a problem
var e = "<my-tag>something 'special'</my-tag>"; //here the " char causes a problem
It works well with a and also c where it finds the tag with the containing text. It also does not find the text in b which is what I want. But in case d and e the tag with content is not found due to the occurrence of the " and ' character. What I want is a regex where inside the tag " is allowed if the string is start with ', and vice versa.
Is it possible to achieve this with one regex, or is the only thing I can do is to work with two separate regex expressions like
/(")*?<my-tag>((.|\n)[^']*?)<\/my-tag>*?(")/g and /(')*?<my-tag>((.|\n)[^"]*?)<\/my-tag>*?(')/g ?
It's not pretty, but I think this would work:
/("<my-tag>((.|\n)[^"]*?)<\/my-tag>"|'<my-tag>((.|\n)[^']*?)<\/my-tag>')/g
You should be able to use de match from the first match ('|") and reuse it for the second match. Something like the following:
/('|")<my-tag>.*?<\/my-tag>\1/g
This should make sure to match the same character at the beginning and the end.
But you really shouldn't use regex for parsing HTML.

Trying to use Javascript regex to grab a section of "&" delimited text whether or not it's the last value

My text looks similar to this:
action=addItem&siteId=4&lang_locale=en_US&country=US&catalogId=1&productId=417689&displaySize=7&skuSize=2194171&qty=1&pil=7&psh=had+AIRJRnjbp7+rGivIKg00
and I want to replace the value of 'psh'. It may sometimes not be the last value (it may be followed by &something=else).
I've tried doing these lines of code:
var text = text.replace(/&psh=.*(?=&|$)/, "&psh=" + data.psh);
var text = text.replace(/&psh=.*(?=[&|$]+)/, "&psh=" + data.psh);
var text = text.replace(/(?:&psh=)(.*)(?=[&|$]+)/, data.psh);
None of them work for both situations. Use this site to check regexes.
This should work:
var text = text.replace(/&psh=[^&]*/, "&psh=" + data.psh);
[^&]* matches a string of any length that consists of any characters except &, therefore the match will continue until the end of the string or until (but not including) the next &, whichever comes first.
Tim's answer may work, but I fear it is not the best possible answer. The string you are giving as an example looks a lot like a url. If it is, that means there can sometimes be a pound sign in it as well (#). To compensate for that you actually need to modify your code to look like this:
var text = text.replace(/&psh=[^&#]*/, "&psh=" + data.psh);
Notice the # which was added in order to not get tripped up by anchor tags in the url.

Categories

Resources