Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I used the replace() function to remove the _pc and keep the 1, but it's not working...
function testing()
{
var code = "a1_pc"; //The initial stuff
alert(code); //Printing -> a1_pc
var number = code.split("a"); //Remove the "a"
alert(number); //Printing again -> ,1_pc
number = number.slice(1); //Remove the ","
alert(number); //Printing again -> 1_pc
number = number.replace("_pc", "");
alert(number); //Returns nothing...
}
Your above solution should work perfectly and does so in the example below.
The problem must lay somewhere else within your code.
var text = '1_pc';
text = text.replace("_pc", "");
console.log(text);
if you are certain it is the replace() function causing the problems, you can use either of these 2 alternatives.
If you know that the last 3 characters are always _pc, you could use substring to find all the other characters instead.
var text = '1_pc';
text = text.substring(0, text.length - 3);
console.log(text);
Or very similiar to the solution above, you could use slice which is essentially a much cleaner version of the substring solution.
var text = '1_pc';
text = text.slice(0, -3);
console.log(text);
You can use split() javascript function and get first occurrence of string.
split("string which you want to",limit as 1 for first occurrence only)
var res = text.split("_",1);
it will return 1
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I wrote a small function to split a string stored in variable data,
var data = "Apple|Banana";
var _res = data.split('|');
After printing _res on the console, it is Printing as Apple,Banana.
I am looking for an output where each String is printed on a newline, like,
Apple
Banana
your variable _res is an Array because it was created after splitting data. Hence it is getting printed as it is.
If you want a newline print, you need to manually do it. See below Code as an example.
Use case when you want to iterate over your input:
var data = 'Apple|Banana'; //Assuming your data variable
var _res = data.split('|');
_res.forEach(function(element) {
console.log(element);
});
Use case when you just want to test in console and alert:
var data = 'Apple|Banana'; //Assuming your data variable
var _res = data.split('|').join('\n');
alert(_res);
console.log(_res);
It sounds like you want the output as a string, in which case you shouldn't use split (which returns an array), but .replace - replace all |s with newlines:
const res = 'Apple|Banana'.replace(/\|/g, '\n');
console.log(res);
Or, with alert:
const res = 'Apple|Banana'.replace(/\|/g, '\n');
alert(res);
You should check Escape notation. You can encode special character which will have special meaning in string.
\n is used to create line breaks in string.You can split() string by , and join() by \n.
let str = 'Apple,Banana'
let newStr = str.split(',').join('\n')
console.log(newStr);
let str = 'Apple,Banana'
document.querySelector('div').innerHTML = str.split(',').join('<br>')
<div><div>
If my understanding to your problem is correct, you want to split the string using "|" and "," characters. In that case you can use pass regex value in your split method parameter.
var _res = d.data.split(/[,|]+/);
You can use this site to generate your regex https://www.regextester.com/
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I might asking a naive question.
But I am stuck. My requirement is do masking of data.
Following is the code snippet :
var str = substr(Test_dat,0,6);
var Test_dat1 = replace(Test_dat,str,"SampleSample");
So basically, "Test_dat" is input string and I am applying substr() function the on incoming data. And then replacing based on masking logic.
If
var Test_dat = "Vikas(vikas)";
var str = substr(Test_dat,0,5);
var Test_dat1 = replace(Test_dat,str,"SampleSample");
Output
SampleSample(vikas)
If
Input
var Test_dat = "Vikas(vikas)";
var str = substr(Test_dat,0,6);
var Test_dat1 = replace(Test_dat,str,"SampleSample");
Error Message
Function call replace is not valid : Unclosed group near index 6
I know it's because of '(' but I am not able to understand how to escape in variable "str".
Any Help!!
Change the way you use substr and replace. This code works well.
var Test_dat = "Vikas(vikas)";
var str = Test_dat.substr(0,6);
var Test_dat1 = Test_dat.replace(str,"SampleSample");
This question already has answers here:
Shorten string without cutting words in JavaScript
(27 answers)
Closed 7 years ago.
I came across lots of Question regarding this , and i found solution for PHP only. There was no solution on this site for jQuery/javascript way of doing it.
What I want to do is I want to show first 100 characters but I dont want to cut the last word, as it would be meaningless.
Like say this is myself is the last words so it we regularly take substring and y is 100th word, then it would cut it like this is my, which would be meaning less. So I want it like this is..
My original code :
jQuery(".block-text .success-inner-content").each(function(){
if(jQuery(this).text().length > 100){
jQuery(this).text(jQuery(this).text().substr(0,98)+'..');
}
});
here block-text .success-inner-content class is in loop producing list of Divs with text within it.
The lastIndexOf method takes a second parameter that determines where the search starts, so you don't need to cut the string down before finding the last space:
jQuery(".block-text .success-inner-content").each(function () {
var text = jQuery(this).text();
if (text.length > 100) {
jQuery(this).text(text.substr(0, text.lastIndexOf(' ', 97)) + '...');
}
});
You can also use the text method instead of each to loop the elements and set the text for each:
jQuery(".block-text .success-inner-content").text(function (i, text) {
return text.length > 100 ? text.substr(0, text.lastIndexOf(' ', 97)) + '...' : text;
});
Or you could do it with regex... Something like this -
var s = 'What I want to do is I want to show first 100 characters but I don't want to cut the last word, as it would be meaningless.';
console.log(s.match(/(.{1,19}\w)\s/)[1]+'...');
This matches any 20 characters, ending with a word character, and followed by a space.
Regards
I solved myself. The solution uses substr() and most importantly lastIndexOf() functions of javascript .
jQuery(".block-text .success-inner-content").each(function () {
if (jQuery(this).text().length > 100) {
var str = jQuery(this).text().substr(0,98);
var wordIndex = str.lastIndexOf(" ");
jQuery(this).text(str.substr(0, wordIndex) + '..');
}
});
This question already has answers here:
Why isn't this split in javascript working?
(2 answers)
Closed 8 years ago.
please, could you help me with my task: I need to replace part of string and probably the best way is regular expression but I don't know, how to make it working. I want to do this:
http://someweb.com/section/&limit=10&page=2
replace page=2 with page=3 so string will be:
http://someweb.com/section/&limit=10&page=3
I tried to do something like this:
// set string in t variable
t.replace('/page=[0-9]/', 'page=$1++') });
Thank you very much for your help :)
In our case first argument should be regexp, but in your variant this is string '/page=[0-9]/' (remove '). In replace you can pass function as second argument, and do with matched data what you want. (for example add +1 to page=)
var str = "http://someweb.com/section/&limit=10&page=2";
str.replace(/page=(\d+)/, function (match, page) {
return 'page=' + (+page + 1); // plus before page converts string to number
});
Example
You can also try below code.
var url = "http://someweb.com/section/&limit=10&page=2",
reExp = /page=([0-9])+/,
result = reExp.exec(url);
url = url.replace(reExp, 'page=' + (+result[1] + 1));
console.log(url)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have this pattern amongst a large garble of HTML:
<td>SIP/159#PBX</td>
I want to match this, getting:
159
as the result. This pattern will always be the same, with the only difference being the number between the "/" and the "#".
I have no idea how to do this in JS Regex. Any ideas?
The regex you can use is like this:
/SIP\/(\d+)#PBX/
This finds:
text SIP
followed by a / (which is escaped so it isn't interpreted as the end of the regex)
followed by one or more digits (captured in a group delineated with parens)
followed by the text #PBX
And, then you pull out the first matched group if there's a match.
And, if you have nothing else to go on other than it's in a <td> in your page, then you can use this generic code that looks at all <td> elements in the page. Ideally, you would use the structure of the page to more clearly target the appropriate <td> cells.
var tds = document.getElementsByTagName("td");
var regex = /SIP\/(\d+)#PBX/;
for (var i = 0; i < tds.length; i++) {
var matches = tds[i].innerHTML.match(regex);
if (matches) {
var number = parseInt(matches[1], 10);
// process the number here
}
}
Working demo: http://jsfiddle.net/jfriend00/vDwfs/
If the HTML is not in your page, but in a string, then you can just use the same regex to search for it in the HTML string. You could bracket it with <td> and </td> if that seems wise based on your context.
var matches, number;
var regex = /SIP\/(\d+)#PBX/g;
while (matches = regex.exec(htmlString)) {
number = parseInt(matches[1], 10);
// process the number here
}
You can analyze the string with the following regular expression:
var result = "<td>SIP/159#PBX</td>".match("\<td\>SIP\/([0-9]+)\#PBX\<\/td\>");
Then, the numbers you want will be stored in result[1]:
alert(result[1]);
The trick is to surround the part of the string that you want to isolate in parentheses. Then, the result of the match function is an array in which the first element is the whole string matched by the regular expression, then a new element for each group enclosed in parentheses.
Assuming you have the string stored in a variable named html
html.match(/SIP\/([0-9]*)\#PBX/g)
try this: "SIP/159#PBX".match(/[^\/]+\/([^#]+)#[\s\S]*/)[1]