replace js with square brackets - javascript

I'm hoping there is a better way to write this? Removing [] square brackets are a problem to me.
alert(CanvasData)//images[]=Base.jpg&images[]=Frame_Clear.png&images[]=Left_Clear.png&images[]=Right_Clear.png&images[]=Lenses_Lenses-Semi-Clear.png&images[]=
var PayName = CanvasData.replace("images[]=", "");
PayName = PayName.replace(/\[.*?\]/g, '');
PayName = PayName.replace(/\&images=/g, ' ');
PayName = PayName.replace(/\.png/g, " &");
PayName = PayName.replace(/\_/g, ' ');
PayName = PayName.substring(8);//remove fist 8 character (Base.jpg)
PayName = PayName.substring(0, PayName.length - 2);//remove last 2 characters // Frame Clear & Left Clear & Right Clear & Lenses Lenses-Semi-Clear &
alert(PayName)// Frame Clear & Left Clear & Right Clear & Lenses Lenses-Semi-Clear
Thanks

Call replace with three global regular expressions, where the first call lists every alternate that should be replaced with nothing (i.e. remove all '=', and 'Base.jpg&'), the second lists alternates that should be replaced with a space ('images[]', '_', and '.png'), and the third ties up your loose ends:
var PayName = CanvasData.replace(/=|Base\.jpg&/g,'')
.replace(/images\[\]|_|\.png/g, ' ')
.replace(/^\s*|\s*&\s*$/g, '');
// => "Frame Clear & Left Clear & Right Clear & Lenses Lenses-Semi-Clear"

try escaping the brackets, otherwise they take on a special meaning (define a character class) for the regular expression.
CanvasData.replace("images\[\]=", "");
You are already doing the same thing, by the way, in the second line of code in the replace section.

If the square brackets [] are always empty, you could do:
var Payname = CanvasData.split("[]").join("");
Obviously that doesn't handle the general case.
What this does, is treat [] as a data separator, and turn the string into a parsed array -- just like parsing "1,3,6,4.5,3" except our comma is a []. Then the array formed by breaking up the string is joined back to a string, with a blank separator. All the [] disappear. But those [occupied] do not.

Related

Split a string based on a condition

I would like to split a spreadsheet cell reference (eg, A10, AB100, ABC5) to two string parts: column reference and row reference.
A10 => A and 10
AB100 => AB and 100 ...
Does anyone know how to do this by string functions?
var res = "AA123";
//Method 1
var arr = res.match(/[a-z]+|[^a-z]+/gi);
document.write(arr[0] + "<br>" + arr[1]);
//Method 2 (as deceze suggested)
var arr = res.match(/([^\d]+)(\d+)/);
document.write("<br>" + arr[1] + "<br>" + arr[2]);
//Note here [^\d] is the same as \D
This is easiest to do with a regular expression (regex). For example:
var ref = "AA100";
var matches = ref.match(/^([a-zA-Z]+)([1-9][0-9]*)$/);
if (matches) {
var column = matches[1];
var row = Number(matches[2]);
console.log(column); // "AA"
console.log(row); // 100
} else {
throw new Error('invalid ref "' + ref + '"');
}
The important part here is the regex literal, /^([a-zA-Z]+)([1-9][0-9]*)$/. I'll walk you through it.
^ anchors the regex to the start of the string. Otherwise you might match something like "123ABC456".
[a-zA-Z]+ matches one or more character from a-z or A-Z.
[1-9][0-9]* matches exactly one character from 1-9, and then zero or more characters from 0-9. This makes sure that the number you are matching never starts with zero (i.e. "A001" is not allowed).
$ anchors the regex to the end of the string, so that you don't match something like "ABC123DEF".
The parentheses around ([a-zA-Z]+) and ([1-9][0-9]*) "capture" the strings inside them, so that we can later find them using matches[1] and matches[2].
This example is strict about only matching valid cell references. If you trust the data you receive to always be valid then you can get away with a less strict regex, but it is good practice to always validate your data anyway in case your data source changes or you use the code somewhere else.
It is also up to you to decide what you want to do if you receive invalid data. In this example I make the script throw an error, but there might be better choices in your situation (e.g. prompt the user to enter another value).

Regext to match any substring longer than 2 characters

regex-pattern-to-match-any-substring-matching exact characters longer-than-two-characters-from-a-provided input,where ever exact string matches
Only pot or potato should be highlighted, instead of ota or ot, when user type pota and click search button.
Please find code below where matched string is highlighted.
// Core function
function buildRegexFor(find) {
var regexStr = find.substr(0,3);
for (var i = 1; i < find.length - 2; i++) {
regexStr = '(' + regexStr + find.substr(i+2,1) + '?|' + find.substr(i,3) + ')';
}
return regexStr;
}
// Handle button click event
document.querySelector('button').onclick = function () {
// (1) read input
var find = document.querySelector('input').value;
var str = document.querySelector('textarea').value;
// (2) build regular expression using above function
var regexStr = buildRegexFor(find);
// (3) apply regular expression to text and highlight all found instances
str = str.replace(new RegExp(regexStr, 'g'), "<strong class='boldtxt'>$1</strong>");
// (4) output
document.querySelector('span').textContent = regexStr;
document.querySelector('div').innerHTML = str;
};
consider "meter & parameter" as one string, if type meter in input box and click search button. meter should be highlighted as well as meter in parameter should highlight.Thanks in advance
Your for loop is set to go from i = 1, while i is less than find.length-2. find.length is 4. 4-2 is 2. So your for loop is set to go from i = 1 while i is less than 2. In other words, it's operating exactly once. I have no idea what you thought that for loop was going to do, but I'm betting that isn't it.
Prior to the for loop, regextr is set equal to the string pot (the first three characters of the find string. The first (and only) time through the for loop, it is set to a new value: the left paren, the existing value (pot), the fourth character of find (a), the question mark, the vertical bar, and three characters from find starting with the second. Put those together, and your regextr comes out to:
(pota?|ota)
That RegEx says to find either the string "pota" (with the a being optional, so "pot" also works) or the string "ota". So any instances of pota, pot, or ota will be found and highlighted.
If you just wanted "pota?", just eliminate the right half of that line inside the for loop. Better yet, replace the entire subroutine with just a line that appends the ? character to the find string.

How to split a string by a character not directly preceded by a character of the same type?

Let's say I have a string: "We.need..to...split.asap". What I would like to do is to split the string by the delimiter ., but I only wish to split by the first . and include any recurring .s in the succeeding token.
Expected output:
["We", "need", ".to", "..split", "asap"]
In other languages, I know that this is possible with a look-behind /(?<!\.)\./ but Javascript unfortunately does not support such a feature.
I am curious to see your answers to this question. Perhaps there is a clever use of look-aheads that presently evades me?
I was considering reversing the string, then re-reversing the tokens, but that seems like too much work for what I am after... plus controversy: How do you reverse a string in place in JavaScript?
Thanks for the help!
Here's a variation of the answer by guest271314 that handles more than two consecutive delimiters:
var text = "We.need.to...split.asap";
var re = /(\.*[^.]+)\./;
var items = text.split(re).filter(function(val) { return val.length > 0; });
It uses the detail that if the split expression includes a capture group, the captured items are included in the returned array. These capture groups are actually the only thing we are interested in; the tokens are all empty strings, which we filter out.
EDIT: Unfortunately there's perhaps one slight bug with this. If the text to be split starts with a delimiter, that will be included in the first token. If that's an issue, it can be remedied with:
var re = /(?:^|(\.*[^.]+))\./;
var items = text.split(re).filter(function(val) { return !!val; });
(I think this regex is ugly and would welcome an improvement.)
You can do this without any lookaheads:
var subject = "We.need.to....split.asap";
var regex = /\.?(\.*[^.]+)/g;
var matches, output = [];
while(matches = regex.exec(subject)) {
output.push(matches[1]);
}
document.write(JSON.stringify(output));
It seemed like it'd work in one line, as it did on https://regex101.com/r/cO1dP3/1, but had to be expanded in the code above because the /g option by default prevents capturing groups from returning with .match (i.e. the correct data was in the capturing groups, but we couldn't immediately access them without doing the above).
See: JavaScript Regex Global Match Groups
An alternative solution with the original one liner (plus one line) is:
document.write(JSON.stringify(
"We.need.to....split.asap".match(/\.?(\.*[^.]+)/g)
.map(function(s) { return s.replace(/^\./, ''); })
));
Take your pick!
Note: This answer can't handle more than 2 consecutive delimiters, since it was written according to the example in the revision 1 of the question, which was not very clear about such cases.
var text = "We.need.to..split.asap";
// split "." if followed by "."
var res = text.split(/\.(?=\.)/).map(function(val, key) {
// if `val[0]` does not begin with "." split "."
// else split "." if not followed by "."
return val[0] !== "." ? val.split(/\./) : val.split(/\.(?!.*\.)/)
});
// concat arrays `res[0]` , `res[1]`
res = res[0].concat(res[1]);
document.write(JSON.stringify(res));

ASCII character not being recognized in if statement

I am trying to get a string from a html page with jquery and this is what I have.
var text = $(this).text();
var key = text.substring(0,1);
if(key == ' ' || key == ' ')
key = text.substring(1,2);
text is this  Home
And I want to skip the space and or the keycode above It appears this code does not work either. It only gets the text.substring(0,1); instead of text.substring(1,2); because the if statement is not catching.= and I am not sure why. Any help would be super awesome! Thanks!
There are several problems with the code in the question. First,   has no special meaning in JavaScript: it is a string literal with six characters. Second, text.substring(1,2) returns simply the second character of text, not all characters from the second one onwards.
Assuming that you wish to remove one leading SPACE or NO-BREAK SPACE (which is what   means in HTML; it is not an Ascii character, by the way), then the following code would work:
var first = text.substring(0, 1);
if(first === ' ' || first === '\u00A0') {
text = text.substring(1, text.length);
}
The notation \u00A0 is a JavaScript escape notation for NO-BREAK SPACE U+00A0.
Should you wish to remove multiple spaces at the start, and perhaps at the end too, some modifications are needed. In that case, using a replace operation with regular expression is probably best.
If you want remove spaces at the beginning (and end) of a string, you can use the trim function
var myvar = " home"
myVar.trim() // --> "home"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

javascript - replace dash (hyphen) with a space

I have been looking for this for a while, and while I have found many responses for changing a space into a dash (hyphen), I haven't found any that go the other direction.
Initially I have:
var str = "This-is-a-news-item-";
I try to replace it with:
str.replace("-", ' ');
And simply display the result:
alert(str);
Right now, it doesn't do anything, so I'm not sure where to turn. I tried reversing some of the existing ones that replace the space with the dash, and that doesn't work either.
Thanks for the help.
This fixes it:
let str = "This-is-a-news-item-";
str = str.replace(/-/g, ' ');
alert(str);
There were two problems with your code:
First, String.replace() doesn’t change the string itself, it returns a changed string.
Second, if you pass a string to the replace function, it will only replace the first instance it encounters. That’s why I passed a regular expression with the g flag, for 'global', so that all instances will be replaced.
replace() returns an new string, and the original string is not modified. You need to do
str = str.replace(/-/g, ' ');
I think the problem you are facing is almost this: -
str = str.replace("-", ' ');
You need to re-assign the result of the replacement to str, to see the reflected change.
From MSDN Javascript reference: -
The result of the replace method is a copy of stringObj after the
specified replacements have been made.
To replace all the -, you would need to use /g modifier with a regex parameter: -
str = str.replace(/-/g, ' ');
var str = "This-is-a-news-item-";
while (str.contains("-")) {
str = str.replace("-", ' ');
}
alert(str);
I found that one use of str.replace() would only replace the first hyphen, so I looped thru while the input string still contained any hyphens, and replaced them all.
http://jsfiddle.net/LGCYF/
In addition to the answers already given you probably want to replace all the occurrences. To do this you will need a regular expression as follows :
str = str.replace(/-/g, ' '); // Replace all '-' with ' '
Use replaceAll() in combo with trim() may meet your needs.
const str = '-This-is-a-news-item-';
console.log(str.replaceAll('-', ' ').trim());
Imagine you end up with double dashes, and want to replace them with a single character and not doubles of the replace character. You can just use array split and array filter and array join.
var str = "This-is---a--news-----item----";
Then to replace all dashes with single spaces, you could do this:
var newStr = str.split('-').filter(function(item) {
item = item ? item.replace(/-/g, ''): item
return item;
}).join(' ');
Now if the string contains double dashes, like '----' then array split will produce an element with 3 dashes in it (because it split on the first dash). So by using this line:
item = item ? item.replace(/-/g, ''): item
The filter method removes those extra dashes so the element will be ignored on the filter iteration. The above line also accounts for if item is already an empty element so it doesn't crash on item.replace.
Then when your string join runs on the filtered elements, you end up with this output:
"This is a news item"
Now if you were using something like knockout.js where you can have computer observables. You could create a computed observable to always calculate "newStr" when "str" changes so you'd always have a version of the string with no dashes even if you change the value of the original input string. Basically they are bound together. I'm sure other JS frameworks can do similar things.
if its array like
arr = ["This-is-one","This-is-two","This-is-three"];
arr.forEach((sing,index) => {
arr[index] = sing.split("-").join(" ")
});
Output will be
['This is one', 'This is two', 'This is three']

Categories

Resources