Javascript Regex convert string - javascript

I am not familiar with Javascript Regex. Can anyone tell me how to convert strings like "Minus162Plus140" into "-162,140", or "Plus162Minus140" into "162,-140" by using match or replace? thanks so much in advance!

Building on the previous answer, you'll also need to handle other cases, like "Plus162Minus140":
text = "Minus162Plus140";
text = text.replace(/^Minus/, "-"); // Handle when Minus comes first
text = text.replace("Minus", ",-"); // And second
text = text.replace(/^Plus/, ""); // Handle when Plus comes first
text = text.replace(/Plus/, ","); // And second
But this approach itself is brittle, and assumes that the string will always be of the form /^(Minus|Plus)\d+(Minus|Plus)\d+$/, which you could validate first with a regular expression:
if (/^(Minus|Plus)\d+(Minus|Plus)\d+$/) {
... do the replacement
} else {
... handle the error
}

You can just use string replace:
text = "Minus162Plus140";
text = text.replace("Minus", ",-");
text = text.replace("Plus", ",+");
console.log(text);
Or regex:
text = "Minus162Plus140";
re = /Plus/;
text = text.replace(re, ',+');
re = /Minus/;
text = text.replace(re, ',-');
// Then to remove the initial comma:
re = /^,/;
text = text.replace(re, '');
console.log(text);

Related

JS What's the fastest way to display one specific line of a list?

In my Javascript code, I get one very long line as a string.
This one line only has around 65'000 letters. Example:
config=123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...
What I have to do is replace all & with an break (\n) first and then pick only the line which starts with "path_of_code=". This line I have to write in a variable.
The part with replace & with an break (\n) I already get it, but the second task I didn't.
var obj = document.getElementById('div_content');
var contentJS= obj.value;
var splittedResult;
splittedResult = contentJS.replace(/&/g, '\n');
What is the fastest way to do it? Please note, the list is usually very long.
It sounds like you want to extract the text after &path_of_code= up until either the end of the string or the next &. That's easily done with a regular expression using a capture group, then using the value of that capture group:
var rex = /&path_of_code=([^&]+)/;
var match = rex.exec(theString);
if (match) {
var text = match[1];
}
Live Example:
var theString = "config=123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...";
var rex = /&path_of_code=([^&]+)/;
var match = rex.exec(theString);
if (match) {
var text = match[1];
console.log(text);
}
Use combination of String.indexOf() and String.substr()
var contentJS= "123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...";
var index = contentJS.indexOf("&path_of_code"),
substr = contentJS.substr(index+1),
res = substr.substr(0, substr.indexOf("&"));
console.log(res)
but the second task I didn't.
You can use filter() and startsWith()
splittedResult = splittedResult.filter(i => i.startsWith('path_of_code='));

How to remove exact word from a string

If I have a string
TestString = "{Item:ABC, Item:DEF, Item:GHI}";
How can I remove all of the "Item:"s.
I have tried to use
msg = TestString.replace(/[\Item:/&]+/g, "");
but this unfortunately removes all the Is, Ts. Es and M,s from any letters that may follow.
How can I remove the exact text
Thanks!
It should be simple, you can directly create a Regex like /Item:/g,
var TestString = "{Item:ABC, Item:DEF, Item:GHI}";
var msg = TestString.replace(/Item:/g, "");
console.log(msg);
You could use
/Item:/g
for replacing Item:.
The fomer regular expression
/[\Item:/&]+/g
used a character class with single letters instead of a string.
var TestString = "{Item:ABC, Item:DEF, Item:GHI}",
msg = TestString.replace(/Item:/g, "");
console.log(msg);

removing BBcode from textarea with Javascript

I'm creating a small javscript for phpBB3 forum, that counts how much character you typed in.
But i need to remove the special characters(which i managed to do so.) and one BBcode: quote
my problem lies with the quote...and the fact that I don't know much about regex.
this is what I managed to do so far but I'm stranded:
http://jsfiddle.net/emjkc/
var text = '';
var char = 0;
text = $('textarea').val();
text = text.replace(/[&\/\\#,+()$~%.'":*?<>{}!?(\r\n|\n|\r)]/gm, '');
char = text.length;
$('div').text(char);
$('textarea').bind('input propertychange', function () {
text = $(this).val();
text = text.replace(/[&\/\\#,+()$~%.'":*?<>{}!?\-\–_;(\r\n|\n|\r)]/gm, '');
char = text.length;
$('div').text(char);
});
You'd better write a parser for that, however if you want to try with regexes, this should do the trick:
text = $('textarea').val();
while (text.match(/\[quote.*\[\/quote\]/i) != null) {
//remove the least inside the innermost found quote tags
text = text.replace(/^(.*)\[quote.*?\[\/quote\](.*)$/gmi, '\$1\$2');
}
// now strip anything non-character
text = text.replace(/[^a-z0-9]/gmi, '');
I'm not sure if this would work, but I think you can replace all bbcodes with a regex like this:
var withoutBBCodes = message.replace(/\[[^\]]*\]/g,"");
It just replaces everything like [any char != ']' goes here]
EDIT: sorry, didn't see that you only want to replace [quote] and not all bbcodes:
var withoutBBQuote = message.replace(/\[[\/]*quote[^\]]*\]/g,"");
EDIT: ok, you also want quoted content removed:
while (message.indexOf("[quote") != -1) {
message = message.replace(/\[quote[^\]]*\]((?!\[[[\/]*quote).)*\[\/quote\]/g,"");
}
I know you already got a solution thanks to #guido but didn't want to leave this answer wrong.

Javascript replace does not replace

The pattern in this code does not replace the parenthesis. I've also tried "/(|)/g".
var re = "/[^a-z]/g",
txt = navsel.options[i].text.split(" ")[0], // here I get the text from a select and I split it.
// What I expect is strings like "(en)" , "(el)" etc
txt = txt.replace(re," ")
Thanks in advance
Your regex is a string, this will try to replace that exact string. Regex objects don't have quotes around them, just the delimiters. Try it like this:
var re = /[^a-z]/g,
txt = navsel.options[i].text.split(" ")[0], // here I get the text from a select and I split it.
txt = txt.replace(re," ");
Or if you prefer strings (and a more explicit type):
var re = new RegExp("[^a-z]", "g")

Using JavaScript's replace() method with global switch on a variable

I can't any example of this after being unable to puzzle out how it would work on my own.
All I want to do is take a string which has been assigned to a value, and use that as the replace match string for all matches.
var replacement = 'i';
var text = 'tieiam';
text = text.replace(replacement, ''); // 'teiam'
text = text.replace(/tieiam/g, ''); // 'team'
How do I use them together??
What you want is to use the RegExp object:
text = text.replace(new RegExp(replacement, 'g'), '');
Simple example of it in action.

Categories

Resources