Samuel Granger
Samuel Granger

Reputation: 35

jQuery: Split String at certain element

I'm creating a read more function.* I want to split my html code at the point where <span id="more-NUMBER"></span> happens. Then I want to move the before and after sections.

The problem I'm running into is writing the regex in a way that can account for the numbers placed in the id. Here's what I'm starting with:

var text = jQuery('p').html().split('<span id="more-/\d+/"></span>');
text[0].appendTo('.red-text');
text[1].appendTo('.blue-text');

Here's a starter Fiddle: https://jsfiddle.net/samwisegrangee/r8c4urht/

*I had one that worked previously when our Wordpress site used a <!--more--> comment to create a read more. You can view that solution here: https://codepen.io/samwisegrangee/pen/aWGJOO

Upvotes: 0

Views: 760

Answers (2)

Andy
Andy

Reputation: 63587

First, a regular expression is denoted by forward slashes (/.../) rather than quotes. Second, in the regex you would need to escape the backslash in </span>.

/<span id="more-\d+"><\/span>/

That's not quite all. Your appends aren't working either, so here's some final corrected code:

var regex = /<span id="more-\d+"><\/span>/;
var text = jQuery('.featured-text p').html().split(regex);
jQuery('.red-text').html(text[0]);
jQuery('.blue-text').html(text[1]);

DEMO

Upvotes: 1

linden2015
linden2015

Reputation: 887

id="more-/\d+/"

Backslash is the escape character. So \" not /". What is the / in more-/ supposed to do?

Working demo.

Upvotes: 0

Related Questions