remove some text after - from string - javascript

I want to remove some text from string or integer using javascipt or jquery..
I have string "flow-[s/c]", "flow-max[s/c]","flow-min[s/c]", "Usage-[s/c]", "temperature"
And I want for each :
"flow", "flow-max","flow-min", "Usage", "temperature"
As you can see. I want to remove all the data after - found expect flow-max and flow-min
What I am doing :
var legendName = $(textElement).text().toLowerCase().replace(" ", "-");
Taking the legend Name example : "flow-[s/c]", "flow-max[s/c]"
var displayVal = legendName.split('-')[0];
remove all the data after - found
But I am not able to add condition for flow-max because at this case I will be having two - and two place like flow-min-[s/c]

var displayVal = $(textElement).text().replace(/\-?\[s\/c\]/, "");
The code /\-?\[s\/c\]/ is a regular expression, where:
/ at the start and end are the delimiters of the expression.
\ is an escape character, indicating that the following character should be taken literally (in our example we need it in front of -, [, / and ] because those are control character for regular expressions).
? means the previous character is optional.
So it replaces an optional dash (-) followed by the text [s/c], with an empty string.

Just use this simple regex /(max|min)\[.*?]|-\[.*?]/g. The regex is simple, if you see what it does separately.
The logic has been separated by | operator.
legendName = legendName.replace(/(max|min)\[.*?]|-\[.*?]/, "$1");

You can use lastoccur = legendName.lastIndexOf("-"); to find the last occur of "-" and then split your string.
Reference: http://www.w3schools.com/jsref/jsref_lastindexof.asp

Related

Having hard time with jQuery and replace string value

Im currently developing a posting [like What's on your mind] feature where im using twemoji plugin for emojis.
For some security reasons, i have to convert the emoji into its alt code/image filename before it stores to the database.
And convert it back to image when its being displayed on the feeds.
In my case I use [emoji=filename.png]
for example i have this string:
var string = "[emoji=1f938.png] [emoji=1f938-200d-2642-fe0f.png] [emoji=26f9-fe0f.png]";
string.replace(/-fe0f.png/g, '.png')
.replace(/\[emoji=(.*?)\]/g,'<img src="https://example.net/images/$1">');
the snippet above is working fine, but the only problem is it removes All -fe0f.png in the filename which causes some broken image.
What I want to achive is to remove the -fe0f.png part only when the filename length is <= 14. or maybe if the file name is consist of something like this: (char)-fe0f.png , but if it has more than (char) like (char)-(char)-(char)-fe0f.png, it should still remain the same..
the result should be:
from
[emoji=1f938.png] [emoji=1f938-200d-2642-fe0f.png] [emoji=26f9-fe0f.png]
to
[emoji=1f938.png] [emoji=1f938-200d-2642-fe0f.png] [emoji=26f9.png]
UPDATE:
I just noticed now that there are filenames like this 30-fe0f-20e3.png
but it needs to remove -fe0f in the middle.
so instead of [emoji=30-fe0f-20e3.png],
i need to have [emoji=30-20e3.png]
The file name length limit is equal to fourteen. Thus, there should be "nine" characters before the "-fe0f"
[^=] means all characters except "="
<![^=])a means there must not "=" before the "a"
<![^=]{9})a means it must not has a "=" character during the nine characters before the letter "a".
(?<![^=]{9})-fe0f.png means it must not has a "=" character during the nine characters before the "-fe0f.png".
So your new code should be like the below:
var string = "[emoji=1f938.png] [emoji=1f938-200d-2642-fe0f.png] [emoji=26f9-fe0f.png]";
string.replace(/(?<![^=]{9})-fe0f.png/g, '.png')
.replace(/\[emoji=(.*?)\]/g,'<img src="https://example.net/images/$1">');
Replacing the data in the example string:
const regex = /(\[emoji=[^\s\]\[]{0,13})-fe0f(\.png)/g;
let string = "[emoji=1f938.png] [emoji=1f938-200d-2642-fe0f.png] [emoji=26f9-fe0f.png]";
string = string.replace(regex, '$1$2');
console.log(string);
You can do the replacement in one replace call with a match and a capture group, matching 0-13 characters after emoji=
\[emoji=([^\s\]\[]{0,13})-fe0f\.png]
The pattern matches:
\[emoji= Match [emoji=
( Capture group 1
[^\s\]\[]{0,13} Match 0-13 times a non whitespace char except for [ and ]
) Close group 1
-fe0f\.png] Match literally (note to escape the dot)
regex demo
const regex = /\[emoji=([^\s\]\[]{0,13})-fe0f\.png]/g;
let string = "[emoji=1f938.png] [emoji=1f938-200d-2642-fe0f.png] [emoji=26f9-fe0f.png]";
string = string.replace(regex, '<img src="https://example.net/images/$1.png">');
console.log(string);
This should do it if you are just trying to not replace for greater than 14 chars.
if (string.length > 14) {
// do your replace here
}
Now, not sure if you are suggesting that if there's more than one "-" that you don't want to replace either.

Regex to get the text between two characters?

I want to replace a text after a forward slash and before a end parantheses excluding the characters.
My text:
<h3>notThisText/IWantToReplaceThis)<h3>
$('h3').text($('h3').text().replace(regEx, 'textReplaced'));
Wanted result after replace:
notThisText/textReplaced)
I have tried
regex = /([^\/]+$)+/ //replaces the parantheses as well
regex = \/([^\)]+) //replaces the slash as well
but as you can see in my comments neither of these excludes both the slash and the end parantheses. Can someone help?
A pattern like /(?<=\/)[^)]+(?=\))/ won't work in JS as its regex engine does not support a lookbehind construct. So, you should use one of the following solutions:
s.replace(/(\/)[^)]+(\))/, '$1textReplaced$2')
s.replace(/(\/)[^)]+(?=\))/, '$1textReplaced')
s.replace(/(\/)[^)]+/, '$1textReplaced')
s.replace(/\/[^)]+\)/, '/textReplaced)')
The (...) forms a capturing group that can be referenced to with $ + number, a backreference, from the replacement pattern. The first solution is consuming / and ), and puts them into capturing groups. If you need to match consecutive, overlapping matches, use the second solution (s.replace(/(\/)[^)]+(?=\))/, '$1textReplaced')). If the ) is not required at the end, the third solution (replace(/(\/)[^)]+/, '$1textReplaced')) will do. The last solution (s.replace(/\/[^)]+\)/, '/textReplaced)')) will work if the / and ) are static values known beforehand.
You can use str.split('/')
var text = 'notThisText/IWantToReplaceThis';
var splited = text.split('/');
splited[1] = 'yourDesireText';
var output = splited.join('/');
console.log(output);
Try Following: In your case startChar='/', endChar = ')', origString=$('h3').text()
function customReplace(startChar, endChar, origString, replaceWith){
var strArray = origString.split(startChar);
return strArray[0] + startChar + replaceWith + endChar;
}
First of all, you didn't define clearly what is the format of the text which you want to replace and the non-replacement part. For example,
Does notThisText contain any slash /?
Does IWantToReplaceThis contain any parentheses )?
Since there are too many uncertainties, the answer here only shows up the pattern exactly matches your example:
yourText.replace(/(\/).*?(\))/g, '$1textReplaced$2')
var text = "notThisText/IWantToReplaceThis";
text = text.replace(/\/.*/, "/whatever");
output : "notThisText/whatever"`

Replace a specific set of characters using JavaScript only

I have an RTF string that contains \*\revtbl{Unknown;}}, it is used to indecate that the word that follows is misspelled (I think) and I need to remove it, when I do:
.replace(/{\*\revtbl{Unknown;}}/g, "")
I get two lines:
*
evtbl{Unknown;}}
When I change to:
.replace(/{\*\r|evtbl{Unknown;}}/g, "")
I get just the * and a second line. e.g.:
var tt = '\*\revtbl{Unknown;}}';
tt=tt.replace(/{\*\r|evtbl{Unknown;}}/g, "");
alert('"'+tt+'"');
I see:
"*
"
I could not find any reference about the use of the pipe | character so I need to know: if by using it am I asking to replace two separate strings one being {\*\r and the other being evtbl{Unknown;}} bottom line I need to replace the literal string \*\revtbl{Unknown;}} with nothing.
I think it is just a matter of escaping all the characters correctly
//sample string - NOTE: the backslashes had to be escaped for JS
var str = "RTF string that contains \\*\\revtbl{Unknown;}}, it is used to indecate that the word that follows is misspelled (I think) and I need to remove it, when I do:";
var regEx = /\\\*\\revtbl\{Unknown;\}\}/g;
console.log(str.replace(regEx, ''));

Splitting a string at special character with JavaScript

I am trying to "intelligently" pre-fill a form, I want to prefill the firstname and lastname inputs based on a user email address, so for example,
jon.doe#email.com RETURNS Jon Doe
jon_doe#email.com RETURN Jon Doe
jon-doe#email.com RETURNS Jon Doe
I have managed to get the string before the #,
var email = letters.substr(0, letters.indexOf('#'));
But cant work out how to split() when the separator can be multiple values, I can do this,
email.split("_")
but how can I split on other email address valid special characters?
JavaScript's string split method can take a regex.
For example the following will split on ., -, and _.
"i-am_john.doe".split(/[.\-_]/)
Returning the following.
["i", "am", "john", "doe"]
You can use a regular expression for what you want to split on. You can for example split on anything that isn't a letter:
var parts = email.split(/[^A-Za-z]/);
Demo: http://jsfiddle.net/Guffa/xt3Lb9e6/
You can split a string using a regular expression. To match ., _ or -, you can use a character class, for example [.\-_]. The syntax for regular expressions in JavaScript is /expression/, so your example would look like:
email.split(/[\.\-_]/);
Note that the backslashes are to prevent . and - being interpreted as special characters. . is a special character class representing any character. In a character class, - can be used to specify ranges, such as [a-z].
If you require a dynamic list of characters to split on, you can build a regular expression using the RegExp constructor. For example:
var specialChars = ['.', '\\-', '_'];
var specialRegex = new RegExp('[' + specialChars.join('') + ']');
email.split(specialRegex);
More information on regular expressions in JavaScript can be found on MDN.
Regular Expressions --
email.split(/[_\.-]/)
This one matches (therefore splits at) any of (a character set, indicated by []) _, ., or -.
Here's a good resource for learning regular expressions: http://qntm.org/files/re/re.html
You can use regex to do it, just provide a list of the characters in square brackets and escape if necessary.
email.split("[_-\.]");
Is that what you mean?
You are correct that you need to use the split function.
Split function works by taking an argument to split the string on. Multiple values can be split via regular expression. For you usage, try something like
var re = /[\._\-]/;
var split = email.split(re, 2);
This should result in an array with two values, first/second name. The second argument is the number of elements returned.
I created a jsFiddle to show how this could be done :
function printName(email){
var name = email.split('#')[0];
// source : http://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript
var returnVal = name.split(/[._-]/g);
return returnVal;
}
http://jsfiddle.net/ts6nx9tt/1/
If you define your seperators, below code can return all alternatives for you.
var arr = ["_",".","-"];
var email = letters.substr(0, letters.indexOf('#'));
arr.map(function(val,index,rest){
var r = email.split(val);
if(r.length > 1){
return r.join(' ');
}
return "";
}
);

How to remove the special characters from a string using javascript

I have the below String value to be displayed in text area and i want to remove the first characters ##*n|n from the string .
The string is as follows :
Symbol-001
##*n|nClaimant Name
##*n|nTransaction
I have used the below code to deal with removing the special characters
var paramVal1 = parent.noteText; //paramVal1 will have the string now
var pattern = /[##*n|n]/g;
var paramVal1 = paramVal1.replace(pattern,'');
document.getElementById("txtNoteArea").value = paramval1;//appending the refined string to text area
For the above used code am getting the out put string as below
Symbol-001
|Claimat Name //here 'n' is missing and i have an extra '|' character
|Transactio //'n' is missing here too and an extra '|' character
Kindly help to remove the characters ##*n|n without affecting the other values
What your regex is saying is "remove any of the following characters: #|*n". Clearly this isn't what you want!
Try this instead: /##\*n\|n/g
This says "remove the literal string ##*n|n". The backslashes remove the special meaning from * and |.
You are using regular expression reserved chars in your pattern, you need to escape them
You can use this expression:
var pattern = /[\#\#\*n\|n]/g;
i think use this /[##*n\|n]/g regEx
If you want to replace the first occurrence as you say on your question, you don't need to use regex. A simple string will do, as long as you escape the asterisk:
var str = "Symbol-001 ##*n|nClaimant Name ##*n|nTransaction";
var str2 = str.replace("##\*n|n", ""); //output: "Symbol-001 Claimant Name ##*n|nTransaction"
If you want to replace all the occurrences, you can use regex, escaping all the characters that have a special meaning:
var str3 = str.replace(/\#\#\*n\|n/g, ""); //output: "Symbol-001 Claimant Name Transaction"
Have a look at this regex builder, might come in handy - http://gskinner.com/RegExr/

Categories