How can i split strings that has prefix and suffix in Javascript? - javascript

I have string that is stored in a variable in this form :
var c = "<p>Let's try with single inputs : *[]*</p>"
I can easily split and convert the *[]* into <span> using this method [a]:
var res = c.split("*[]*");
if(res.length > 1){
var strContent = res[0];
var inptSoal = ' <span id="content-input" class="al question mb-0">[ ]</span> ';
strContent += inptSoal;
strContent += res[1];
c = strContent;
} return c;
But now, let's say that i have this form of string [b] :
var c = "<p>Let's try with 2 inputs : *[Input 1]* and *[Input 2]*</p>"
How can i split (and convert) every *[ and ]* (that has strings inside of it) into HTML <span> element? Thanks in advance
EDIT
To make it clearer, using the method i write above ([a]) it will return this in my website :
What i want to do is to return the same result if the condition is like the second form ([b]) i mentioned above. How can i achieve this?
SOLVED ✅
Every answers here solved my problem. The first answer here was Ofek's answer. It works well, what i need to do to achieve the result i want is only to change the "<span>" + input + "</span>" inside the replace() function into :
"<span id='content-input' class='al question mb-0'>" + input + "</span>" to make the span element has the CSS Style like my screenshot above.
Other two answers, sid's answer and Rahul Kumar's answer also works well. But i prefer to choose Rahul Kumar's answer for its simplicity.
Thanks in advance to everyone that answered my questions!

Use regex to match the pattern and pass it to String.replace() method to replace the matched pattern in your string with new string <span>$1</span>. Here $1 indicates the captured group which is a content inside brackets *[...]*.
str = "<p>Let's try with 2 inputs : *[Input 1]* and *[Input 2]*</p>"
const regex = /\*\[(.*?)\]\*/g;
const finalStr = str.replace(regex, "<span>$1</span>");
console.log(finalStr);

You can use this method:
function replaceWithInput(str, replacer) {
var arr = str.split("*[");
for (var i = 1; i < arr.length; i++) {
var index = arr[i].indexOf("]*");
arr[i] = replacer(arr[i].slice(0, index)) + arr[i].slice(index + 2);
}
return arr.join("");
}
you use it like so:
function replace(input) {
return "<span>" + input + "</span>"
}
replaceWithInput("<p>Let's try with 2 inputs : *[Input 1]* and *[Input 2]*</p>", replace);

Using Regex you could do,
let c = "<p>Let's try with 2 inputs : *[Input 1]* and *[Input 2]*</p>";
let newC = c.replace(/\*([[])/g, '<span>');
let newC2 = newC.replace(/\]([*])/g, '</span>');
console.log(newC2);

Related

Split a query string by "&" but some attribute has this "&" in the value

I try to split an query by "&", but some attribute also has this "&" in the value, may I know how to split it? For example:
const query = "attr1=value1&attr2=va & lu&e2&attr3=value3"
May I know how to split the query into an array without splitting the "va & lu&e2":
["attr1=value1", "attr2=va &%lu&e2", "attr3=value3"]
Thanks!
if you want to use these parameters on a query,
you should use encodeURIComponent() which will escape the string so it can be used as a value in a query.
const query = "attr1=" + value1 +
"&attr2=" + encodeURIComponent("va & lu&e2") +
"&attr3=" + value3
This will result in the following string:
"attr1=value1&attr2=va%20%26%20lu%26e2&attr3=value3"
So every '&' is encoded as '%26'
To split it you can now rely on the '&' sign:
const splitArray = query.split('&')
Although, I would use the encodeURIComponent() for every query parameter value. unless I know exactly which value I use and that it doesn't need escaping.
you could mark & differently when you are using it as a value: something like & for example and then create your own function for splitting.
like:
var acc = query[0];
var splitted = [];
for(let i = 1; i < query.length; i++) {
if(query[i] === '&' && query[i-1] !== '\') {
splitted.push(acc);
acc = "";
} else {
acc += query[i];
}
}
the code probably does not work, but hopes this can clarify something

Remove the last element's specific text

For example i have a for loop which will generate some kind of words
for(var i=0;i<profile.test.length;i++){
var wordList = wordList + profile.test[i].text.map(function(k) {
return k.split(/,\s*/).join('+');
}).join(' , ') + '|';
};
and this will return something like
hhh1+hhhh2|fdsg+gsdg , 123+1232|
but i want to remove the last "|"
hhh1+hhhh2|fdsg+gsdg , 123+1232
how could i do that?
You can change '|' to
i !== profile.test.length - 1 ? '|' : ''
which would change your code to:
for(var i=0;i<profile.test.length;i++){
var wordList = wordList + profile.test[i].text.map(function(k) {
return k.split(/,\s*/).join('+');
}).join(' , ') + (i !== (profile.test.length - 1) ? '|' : '');
};
If you have the outer loop return an array you can use join on it.
This works because join takes the elements of an array and "joins" them together into a single string using the passed in argument as the delimiter/separator.
This means that var example = ['a', 'b', 'c'].join('|') sets example to 'a|b|c'.
Without knowing the value of profile in your example it's hard to refactor your code an know that it works. But, if you modify your existing code you should be able to do something along the lines of this:
profile.test.map(function(item) {
return item.map(function(k) {
return k.split(/,\s*/).join('+');
}).join(' , ')
}.join('|');
Here's another example of a similar problem that works using the same concept as mentioned above:
// hhh1 , hhhh2|fdsg , gsdg
var items = [{text:'hhh1, hhhh2'}, {text: 'fdsg, gsdg'}]
var out = items.map(function(item) {
return item.text.split(/,\s*/).join(' , ');
}).join('|');
console.log(out)
You can use the substr method of the generated String to remove the last character:
wordList = wordList.substr(0, wordList.length -1);
A general solution when the last "|" isnt the last character would be by define its position could be like this:
str ="abc|def|ghi|nope";
var lastPos = str.lastIndexOf('|');
var wordStart = str.substring(0,lastPos);
var wordEnd = str.substring(lastPos+1);
alert(wordStart + wordEnd);
JSFiddle:
https://jsfiddle.net/e59erp0h/
In real word szenarios, id recomment to shorten it (unless you want to play arond with ANYTHING ;)(
Add this code after your loop to remove the last character
wordList = wordList.substring(0, wordList.length - 2);

Javascript Regex - Converting string to number

I have string where I want to remove any letters and hyphens. I have a code like below,
var s = '-9d 4h 3m',
t = '1-22';
var p = /[^0-9-]+/g;
r = s.replace(p, ''),
a = t.replace(p, '');
console.log(r, a);
Here I want to remove hyphen if it is in between the numbers and omit at first. Any help or suggestions?
Fiddle
Much more simpler one without using | operator.
string.replace(/(?!^-)\D/g, "")
DEMO
You can use the following regex:
var p = /[^0-9-]+|(?:(?!^)-)/g;
See Fiddle
In your console log you put a comma between the variable but you need a plus like this.
I have also change variable a so that it removes the -
var s = '-9d 4h 3m';
var t = '1-22';
var p = /[^0-9-]+/g;
var r = s.replace(p, '');
var a = t.replace("-", '');
console.log(r + " " + a);
https://stackoverflow.com/a/1862219/3464552 check over here this will be a solution.
var s = '-9d 4h 3m',
s = s.replace(/\D/g,'');

Javascript splitting string in to two parts number and text safely

I was wondering if there is a safe way (if the data is coming from users) to get the string and the number separated - for example "something-55", "something-124", "something-1291293"
I would want:
something and
55
something and
124
something and
1291293
I mean by a 'safe way' is to be certain I am getting only the number on the end.. if the data is coming from the users "something" could be anything some-thing-55 for example..
I'm looking for a robust way.
try this, working.
var string = 'something-456';
var array = string.split('-');
for (var i = 0;i<array.length;i++){
var number = parseFloat(array[i]);
if(!isNaN(number)){
var myNumber = number;
var mySomething = array[i - 1];
console.log('myNumber= ' + myNumber);
console.log('mySomething= ' + mySomething);
}
}
Can you try this?
var input='whatever-you-want-to-parse-324';
var sections=input.split(/[\w]+-/);
alert(sections[sections.length-1]);
You can use substr along with lastIndexOf:
var str = "something-somethingelse-55",
text = str.substr(0, str.lastIndexOf('-')),
number = str.substr(str.lastIndexOf('-') + 1);
console.log(text + " and " + number);
Fiddle Demo
All though it's a tad late, this would be the most restrictive solution:
var regex = /^([-\w])+?-(\d+)$/,
text = "foo-123",
match = test.match(regex);
You will get a match object back with the following values:
[ "foo-123", "foo", "123" ]
It's a very strict match so that " foo-123" and "foo-123 " would not match, and it requires the string to end in one or more digits.

How do I delete a '_' prefix on a variable using jQuery?

I have a variable that reads as _123456 and I need to delete the underscore prefix on this variable before storing it to a field. How do I do this?
var value = "_123456"
value.substr(1)
No need for jQuery!
This is just generic Javascript, not specific to jQuery. You'd do something like this:
var result = value.substring(1);
Or...
var result = value.replace(/^_/, '');
Or... (if there can be more than one underscore)
var result = value.replace(/^_+/, '');
var value = "_123456"
var trimmed = value.substring(1); // "123456"
[not recommended]
To do this with jQuery (and an if):
var element = $('<div></div>');
var text = "_123456";
for(var i = 0; i < text.length; i++) {
if ( i > 0 ) {
element.append('<span>' + text[i] + '</span>');
}
}
var trimmed = element.text();
I tried element.remove(':first') instead of the if, but it didn't seem to work. No idea why.
FYI - If the underscore is after the digits then you could use parseInt()
var value = "123456_"
So for example parseInt("123456_") will return the number 123456.

Categories