Returning a String with whitespaces - javascript

I am using the below string and I want to return the substring with the blankspaces in javascript.
How can I do this?
As of now I used the normal substring function but its giving me the result after removing the blankspaces.
var Sting="CREC 20140615001CREC_GLOSS 18_0000033122 GLO4265 SGLB201406152014090120140531 TESTFOREF 0000000000033122 8-1 EQTY GB 21419 ACTUALS EUR000000000462098830 8738 N C70390000501F SQTY BUY 212102 49500.00# 9.34 8738 8738 "
var x= Sting.substring(1,27)
Result x= CREC 20
I don't want it like this, rather, I want my result to be
x= CREC 20

This is a browser thing - consecutive spaces are displayed as one. You might want to replace ' ' with and then it will display all spaces indiviudaly
x.replace(" ", " ");
Another way is to avoid displaying the string as HTML. For example the alert() function will show the correct number of spaces without the need to replace. Also displaying the string within a <pre> tag should work fine too.

I think Dobromir's interpretation of the OP is probably correct, and therefore a good answer.
If it is indeed a browser thing, then perhaps a better way to get it to display properly without changing the string itself is to style the HTML element with
white-space: pre
This will preserve the spaces like it does in a <pre> block.
See http://www.w3schools.com/cssref/pr_text_white-space.asp

If your spaces are always the same length you could do:
x.replace(" ", " ");
otherwise you can use a regular expression to replace multiple spaces with one:
x.replace(/\s+/g, ' ');
as seen Here

Related

Repeat a javascript replace until no change is made?

I have a short but complex regular expression to trim spaces regardless of html tags present in the string.
var text = "<span><span>ex ample </span> </span>";
// trim from start; not relevant in this example
text = text.replace(/^((<[^>]*>)*)\s+/g, "$1");
// trim from end
text = text.replace(/\s+((<[^>]*>)*)$/g, "$1");
console.log(text);
<span><span>ex ample </span> </span> - example input
<span><span>ex ample</span></span> - expected output
<span><span>ex ample </span></span> - observed output
How do I achieve my expected output?
I've tried adding the /g flag because it should supposedly match more than once and that should fix it (running the replace twice does work for the example) but it doesn't seem to repeat anything at all.
Alternative ways to trim strings regardless of tags are also appreciated because that is my primary objective. The secondary objective is learning why this didn't work.
You need to add some meaning to your tags, some need their spaces, some don't.
Try this:
text.replace(/\s*(<\/?(span|div)>)\s*/g, "$1")
.trim()
.replace(/\s+/g, ' ');
It:
replaces spaces around tags "surrounding" content
trims spaces around global string
removes redundant spaces
The list of "surrounding" tags can be changed to include things like tr...
Steps 2 and 3 might come first to speed things up.
Tried it with:
var text = "<div> <i>ano</i> <b>ther</b> <span> <b>my</b> <i>ex</i> <u> ample </u> </span> </div>";
First answer, prior to comments.
The idea is to remove all spaces between:
a non-space character and an opening tag
a closing tag and a non-space character
text.replace(/([^\s])\s*(<)/g, "$1$2")
.replace(/([>])\s*([^\s])/g, "$1$2")
.trim();
Preamble: don't just copy this, read to the end.
Thinking from the other way around - by replacing until no match is found instead of until no change is made, this seems to work very simply.
var text = "<span><span>ex ample </span> </span>";
var trim_start = /^((<[^>]*>)*)\s+/;
while(text.match(trim_start)) {
text = text.replace(trim_start, "$1");
}
var trim_end = /\s+((<[^>]*>)*)$/;
while (text.match(trim_end)) {
text = text.replace(trim_end, "$1");
}
console.log(text);
The output is as expected - the only space is between ex ample
But this has a big problem if the replace might not change anything. Simply changing \s+ to \s* makes it turn into an infinite cycle. So, all in all, it works for my case but is not robust and to use it, you must be completely sure every single replace will change something when the regex matches.

Regex to replace certain characters on first line

I'm thinking that this is something very simple, but I can't find an answer anywhere online. I've found results on how to match the whole first line in a multiline string, but not how to find all occurrences of a certain character ONLY on the first line.
So for instance:
HelloX dXudXe
How areX yXou?
FxIXne?
Matching all capital Xs only on the first line, and replacing that with nothing would result in:
Hello dude
How areX yXou?
FxIXne?
This matches only the first X:
/X/m
This matches all Xs:
/X/g
So I'm guessing the answer is the regex version of one of these statements:
"Replace all X characters until you find a newline"
"Replace all X characters in the first line"
This sounds like such a simple task, is it? And if so, how can it be done? I've spent hours looking for a solution, but I'm thinking that maybe I don't get the regex logic at all.
Without knowing the exact language you are using, it's difficult to give an example, but the theory is simple:
If you have a complex task, break it down.
In this case, you want to do something to the first line only. So, proceed in two steps:
Identify the first line
Perform an operation on it.
Using JavaScript as an example here, your code might look like:
var input =
"HelloX dXudXe" + "\n" +
"How areX yXou?" + "\n" +
"FxIXne?";
var result = input.replace(/^.*/,function(m) {
return m.replace(/X/g,'');
});
See how first I grab the first line, then I operate on it? This breaking down of problems is a great skill to learn ;)
Split the string into multiple lines, do the replacement on the first line, then rejoin them.
var lines = input.split('\n');
lines[0] = lines[0].replace(/X/g, '');
input = lines.join('\n');

Parsing Text with jQuery

I'm attempting to parse a text string with jQuery and to make a variable out of it. The string is below:
Publications Deadlines: armadllo
I'm trying to just get everything past "Publications Deadlines: ", so it includes whatever the name is, regardless of how long or how many words it is.
I'm getting the text via a the jQuery .text() function like so:
$('.label_im_getting').text()
I feel like this may be a simple solution that I just can't put together. Traditional JS is fine as well if it's more efficient than JQ!
Try this,
Live Demo
First part
str = $.trim($('.label_im_getting').text().split(':')[0]);
Second part
str = $.trim($('.label_im_getting').text().split(':')[1]);
var string = input.split(':') // splits in two halfs based on the position of ':'
string = input[1] // take the second half
string = string.replace(/ /g, ''); // removes all the spaces.

use regex to replace all but first occurrence of a substring of blanks

The following statement runs fine:
$wb.upLinearLoad.append('<div>' + sprintf("%5s%8.1f to%7.1f%8.1f%6.0f%8.0f",sLinearSegName[i][j],fLinearPtBA[i][j],fLinearPtBA[i][j+1],fLen,fLinearPtPpi[i][j],fLinearSegMaxWt[i][j]).replace(/ /," ") + '</div>');
However, I now have a need to dynamically change the color of the last two variables only, so I decided to enclose them in a span with a class='wt' to control their color. This gives:
$wb.upLinearLoad.append('<div>' + sprintf("%5s%8.1f to%7.1f%8.1f<span class='wt'>%6.0f%8.0f</span>",sLinearSegName[i][j],fLinearPtBA[i][j],fLinearPtBA[i][j+1],fLen,fLinearPtPpi[i][j],fLinearSegMaxWt[i][j]).replace(/ /," ") + '</div>');
which fails because the space between span and class gets changed to
My regex ability goes only as far the example, so the question becomes how do I change all but the first space to ?
Any and all suggestions are most welcome, and especially if you see that my whole approach is poor.
Just don't do it using strings. Instead, use the jQuery/DOM manipulation. It's less prone to error and more efficient.
$wb.upLinearLoad.append(
$('<div>').append(
sprintf("%5s%8.1f to%7.1f%8.1f", sLinearSegName[i][j], fLinearPtBA[i][j], fLinearPtBA[i][j+1], fLen),
$('<span>').addClass('wt').text(sprintf("%6.0f%8.0f</span>", fLinearPtPpi[i][j], fLinearSegMaxWt[i][j]))[0]
)
);

Javascript Regex: replacing the last dot for a comma

I have the following code:
var x = "100.007"
x = String(parseFloat(x).toFixed(2));
return x
=> 100.01
This works awesomely just how I want it to work. I just want a tiny addition, which is something like:
var x = "100,007"
x.replace(",", ".")
x.replace
x = String(parseFloat(x).toFixed(2));
x.replace(".", ",")
return x
=> 100,01
However, this code will replace the first occurrence of the ",", where I want to catch the last one. Any help would be appreciated.
You can do it with a regular expression:
x = x.replace(/,([^,]*)$/, ".$1");
That regular expression matches a comma followed by any amount of text not including a comma. The replacement string is just a period followed by whatever it was that came after the original last comma. Other commas preceding it in the string won't be affected.
Now, if you're really converting numbers formatted in "European style" (for lack of a better term), you're also going to need to worry about the "." characters in places where a "U.S. style" number would have commas. I think you would probably just want to get rid of them:
x = x.replace(/\./g, '');
When you use the ".replace()" function on a string, you should understand that it returns the modified string. It does not modify the original string, however, so a statement like:
x.replace(/something/, "something else");
has no effect on the value of "x".
You can use a regexp. You want to replace the last ',', so the basic idea is to replace the ',' for which there's no ',' after.
x.replace(/,([^,]*)$/, ".$1");
Will return what you want :-).
You could do it using the lastIndexOf() function to find the last occurrence of the , and replace it.
The alternative is to use a regular expression with the end of line marker:
myOldString.replace(/,([^,]*)$/, ".$1");
You can use lastIndexOf to find the last occurence of ,. Then you can use slice to put the part before and after the , together with a . inbetween.
You don't need to worry about whether or not it's the last ".", because there is only one. JavaScript doesn't store numbers internally with comma or dot-delimited sets.

Categories